latitude and longitude values giving null - java

I am a newcomer for android programming and stack overflow. MY problem here is mylongitudey in onclick method is giving null value. I have 3 activities.Below one is one among them. I want the latitude and longitude from google map and to send those points into another activity. The main problem here is, it is not giving the latitude and longitude value instead Toasting null value. I couldn't find what was the mistake . Can anyone help me? Thanks in advanced.
SharedPreferences points;
SharedPreferences.Editor ed;
Address returnedAddress;
double mylongitudey,mylatitudey;
String latilongi;
ImageView iv;
Button manual,proceed;
GoogleMap map;
LatLng mylat ;
String latlong;
Marker mymarker;
boolean markerclicked;
double mylatitudeyd,mylongitudeyd;
String addstringaa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.two_buttons);
actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
getActionBar().setDisplayHomeAsUpEnabled(true);
Toast.makeText(this,"Please select the destination by long click", Toast.LENGTH_LONG).show();
LatLng mylat;
final GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setOnMarkerDragListener(this);
map.setTrafficEnabled(true);
// map.setOnMyLocationButtonClickListener(this);
SharedPreferences shared = getSharedPreferences("map", 0);
String mylats = (shared.getString("twolati", "NoValue"));
String mylong= (shared.getString("twolong", "NoValue"));
double dmylats = Double.valueOf(mylats);
double dmylong = Double.valueOf(mylong);
map.animateCamera(CameraUpdateFactory.zoomTo(15));
mylat = new LatLng(dmylats, dmylong);
try {
Toast.makeText(this, "This is"+mylats,Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this,"problem in mylat",0);
e.printStackTrace();
}
map.moveCamera(CameraUpdateFactory.newLatLngZoom(mylat, 13));
map.addMarker(new MarkerOptions().position(mylat).title("You are Here"));
markerclicked=false;
//onMyLocationButtonClick();
map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
if(markerclicked==false)
{
mymarker = map.addMarker(new MarkerOptions().position(arg0).title("Your Destination").draggable(true));
markerclicked=true;
}else{
Toast.makeText(getApplicationContext(), "Marker Aready Set..!", Toast.LENGTH_LONG).show();
}
}
});
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
LatLng mylatlong;
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
mylongitudey = arg0.getLongitude();
mylatitudey = arg0.getLatitude();
mylatlong = new LatLng(arg0.getLatitude(), arg0.getLongitude());
//sourcepoint=String.format(" ",mylat);
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(mylat,1));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(mylatlong, 14));
}
});
// Toast.makeText(this, getmapid, Toast.LENGTH_LONG).show();
SharedPreferences pr= getSharedPreferences("reserve", 0);
latilongi=pr.getString("sourcepoint", "sourcepoint");
manual=(Button)findViewById(R.id.manuel);
manual.setOnClickListener(this);
proceed=(Button)findViewById(R.id.proceed);
proceed.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
// Toast.makeText(MainActivity.this, item.getTitle(),
// Toast.LENGTH_LONG).show();
switch (item.getItemId()) {
case android.R.id.home:
if (getParentActivityIntent() == null) {
Log.i("tag", "You have forgotten to specify the parentActivityName in the AndroidManifest!");
onBackPressed();
} else {
NavUtils.navigateUpFromSameTask(this);
}
return true;
case R.id.action_refresh:
// refresh
Intent intent = new Intent(Drop_Off_Location.this, Main.class);
startActivityForResult(intent, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
try {
if (v.getId() == R.id.proceed) {
/* Toast.makeText(this, "address"+mylongitudey, 0);
Toast.makeText(this, " destination in DOL class "+addstringaa, 0).show();*/
points= getSharedPreferences("map", 0);
ed=points.edit();
String twolatitudey = String.valueOf(mylatitudey);
String twolongitudey = String.valueOf(mylongitudey);
ed.putString("twolatitudey",twolatitudey);
ed.putString("twolongitudey", twolongitudey);
ed.commit();
Toast.makeText(this, "dest longitude"+mylongitudey, Toast.LENGTH_LONG).show();
Intent intent = new Intent(Drop_Off_Location.this,Autofill.class);
startActivity(intent);
}
else if(v.getId()==R.id.manuel)
{
Intent intent = new Intent(Drop_Off_Location.this,Reserve.class);
startActivity(intent);
}
} catch (Exception e) {
Toast.makeText(this,"error in onclick"+e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
Logcat verbose:
10-08 02:23:53.965: D/dalvikvm(3221): GC_FOR_ALLOC freed 111K, 25% free 7167K/9528K, paused 132ms, total 134ms
10-08 02:23:53.975: I/dalvikvm-heap(3221): Grow heap (frag case) to 9.411MB for 2457616-byte allocation
10-08 02:23:54.145: D/dalvikvm(3221): GC_FOR_ALLOC freed 2K, 20% free 9565K/11932K, paused 167ms, total 167ms
10-08 02:23:55.895: W/System.err(3221): java.io.IOException: Service not Available
10-08 02:23:55.895: W/System.err(3221): at android.location.Geocoder.getFromLocation(Geocoder.java:136)
10-08 02:23:55.905: W/System.err(3221): at jasperit.atlcitylimo.Autofill.onCreate(Autofill.java:189)
10-08 02:23:55.905: W/System.err(3221): at android.app.Activity.performCreate(Activity.java:5231)
10-08 02:23:55.905: W/System.err(3221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 02:23:55.905: W/System.err(3221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 02:23:55.905: W/System.err(3221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 02:23:55.905: W/System.err(3221): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 02:23:55.905: W/System.err(3221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 02:23:55.905: W/System.err(3221): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 02:23:55.905: W/System.err(3221): at android.os.Looper.loop(Looper.java:136)
10-08 02:23:55.905: W/System.err(3221): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 02:23:55.905: W/System.err(3221): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 02:23:55.915: W/System.err(3221): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 02:23:55.915: W/System.err(3221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 02:23:55.915: W/System.err(3221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 02:23:55.915: W/System.err(3221): at dalvik.system.NativeStart.main(Native Method)
10-08 02:23:56.015: W/System.err(3221): java.io.IOException: Service not Available
10-08 02:23:56.015: W/System.err(3221): at android.location.Geocoder.getFromLocation(Geocoder.java:136)
10-08 02:23:56.035: W/System.err(3221): at jasperit.atlcitylimo.Autofill.onCreate(Autofill.java:227)
10-08 02:23:56.035: W/System.err(3221): at android.app.Activity.performCreate(Activity.java:5231)
10-08 02:23:56.035: W/System.err(3221): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 02:23:56.045: W/System.err(3221): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 02:23:56.045: W/System.err(3221): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 02:23:56.045: W/System.err(3221): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 02:23:56.045: W/System.err(3221): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 02:23:56.045: W/System.err(3221): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 02:23:56.045: W/System.err(3221): at android.os.Looper.loop(Looper.java:136)
10-08 02:23:56.085: W/System.err(3221): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 02:23:56.085: W/System.err(3221): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 02:23:56.085: W/System.err(3221): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 02:23:56.085: W/System.err(3221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 02:23:56.095: W/System.err(3221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 02:23:56.095: W/System.err(3221): at dalvik.system.NativeStart.main(Native Method)
10-08 02:23:56.255: I/Choreographer(3221): Skipped 688 frames! The application may be doing too much work on its main thread.
10-08 02:23:57.585: I/Choreographer(3221): Skipped 267 frames! The application may be doing too much work on its main thread.
10-08 02:23:58.885: I/Choreographer(3221): Skipped 114 frames! The application may be doing too much work on its main thread.
10-08 02:23:59.675: I/Choreographer(3221): Skipped 107 frames! The application may be doing too much work on its main thread.

//instance variables
private GoogleMap googleMap;
private double longitude = 0.0;
private double latitude = 0.0;
private LocationManager locationManager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // your layout
try {
initilizeMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, this);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap(); //provide your id
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
longitude = location.getLongitude();
latitude = location.getLatitude();
//System.out.println(latitude+ " "+longitude );
if(!isStopFocusEnabled){
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(latitude, longitude)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
In Manifest below code must be there
<permission
android:name="com.ani.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.ani.map.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Goolge API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="YOUR KEY" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
// Change it accordingly.... it will definitely work...

public boolean onTouchEvent(MotionEvent event)
{
int X = (int)event.getX();
int Y = (int)event.getY();
GeoPoint geoPoint = mapView.getProjection().fromPixels(X, Y);
}

Related

Camera.open() error -13 on emulator

I've been trying develop a custom camera application for my project. I have followed pretty much every steps on the android developers website for the deprecated android.hardware.Camera class, as I need to stay compatible for older devices. I have added the permission for the camera and the features for the camera and the autofocus. I am currently testing with the emulator provided by android studio, the Nexus 5 API 23 x86 with both front-facing and back-facing cameras set on emulated. When my code reaches the Camera.open() bit, I get the error -13: Fail to connect to camera service.
I moved my camera initialization at many places but it always throws that error and returns null. The built-in Camera app in the emulator does work properly for both camera and they are both detected in my code. I simply cannot find why it doesn't work.
Here's my code just in case:
CameraActivity.java
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class CameraActivity extends AppCompatActivity {
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final int UI_ANIMATION_DELAY = 300;
private View mControlsView;
private boolean mVisible;
private CameraView mCameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mCameraView = new CameraView(this);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_view);
preview.addView(mCameraView);
// Set up the user interaction to manually show or hide the system UI.
mCameraView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.capture_button).setOnTouchListener(mDelayHideTouchListener);
//// TODO: 2015-11-05 Create a preview class extending SurfaceView and implementing SurfaceHolder.callback and put camera code there
//// TODO: 2015-11-05 http://developer.android.com/guide/topics/media/camera.html#custom-camera
//// TODO: 2015-11-05 http://stackoverflow.com/questions/26305107/how-to-fix-fail-to-connect-to-camera-service-exception-in-android-emulator
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
#Override
protected void onPause(){
super.onPause();
mCameraView.releaseCamera();
}
}
CameraView.java
import android.hardware.Camera; //This is the good import!
/**
* TODO: document your custom view class.
*/
#SuppressWarnings("deprecation")
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context) {
super(context);
try{
mCamera = Camera.open();
} catch (Exception e){
Log.e("CameraView", "Error creating camera: " + e.getMessage());
}
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e){
Log.d("surfaceCreated", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e) {
//Non-existent o.O
}
//Resize, etc
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("CameraView", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCamera != null)
mCamera.stopPreview();
}
public void releaseCamera(){
if(mCamera != null){
mCamera.release();
mCamera = null;
}
}
}
The logcat:
11-09 14:13:13.144 7791-7791/? I/art: Not late-enabling -Xcheck:jni (already on)
11-09 14:13:13.144 7791-7791/? I/art: Late-enabling JIT
11-09 14:13:13.146 7791-7791/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-09 14:13:13.212 7791-7791/com.weebly.olipro007.cameracontrol W/System: ClassLoader referenced unknown path: /data/app/com.weebly.olipro007.cameracontrol-1/lib/x86
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol W/CameraBase: An error occurred while connecting to camera: 0
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol E/CameraView: Error creating camera: Fail to connect to camera service
11-09 14:13:13.489 7791-7820/com.weebly.olipro007.cameracontrol D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-09 14:13:13.508 7791-7791/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab645030, tid 7791
11-09 14:13:13.584 7791-7820/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab6451c0, tid 7820
11-09 14:13:13.611 7791-7820/com.weebly.olipro007.cameracontrol I/OpenGLRenderer: Initialized EGL, version 1.4
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/EGL_emulation: eglSurfaceAttrib not implemented
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdff9a0, error=EGL_SUCCESS
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol D/AndroidRuntime: Shutting down VM
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: FATAL EXCEPTION: main
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: Process: com.weebly.olipro007.cameracontrol, PID: 7791
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.weebly.olipro007.cameracontrol.CameraView.surfaceCreated(CameraView.java:43)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView.updateWindow(SurfaceView.java:582)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:177)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2055)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:670)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:606)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-09 14:13:16.909 7791-7791/? I/Process: Sending signal. PID: 7791 SIG: 9
Well it seems that the service was completely blocked for the old api in Marshmallow. I switched the emulator to lollipop and it loads...

Having Problems with Collection in android

I am having some problems with implementation of Collection in android. The code is given below. I compare the position chosen in an alert dialog and accordingly call collection and its related function. But there seems to be problem and java.lang NullPointerException occurs all the time. i Call these Collection functions at the OnCreate method of the Applciation Start-Up Activity.
private void onStartPref() {
// TODO Auto-generated method stub
// try {
SharedPreferences pref2 = getApplication().getSharedPreferences(
"MyPref", MODE_PRIVATE);
int loadPosition = pref2.getInt("MyKey", isChecked);
Toast.makeText(getApplicationContext(), "Position : " + loadPosition,
Toast.LENGTH_LONG).show();
if (pref2.contains("MyKey")) {
Toast.makeText(getApplicationContext(), "IF" + loadPosition,
Toast.LENGTH_LONG).show();
if (loadPosition == 0) {
Collections.reverse(applist);
Toast.makeText(getApplicationContext(),
"Reverses the present order list", Toast.LENGTH_SHORT)
.show();
} else if (loadPosition == 1) {
Collections.sort(applist,
new ApplicationInfo.DisplayNameComparator(
packageManager));
Toast.makeText(getApplicationContext(), "Sorts Alphabetically",
Toast.LENGTH_SHORT).show();
} else if (loadPosition == 2) {
Collections.shuffle(applist);
Toast.makeText(getApplicationContext(),
"Shuffles the present order selected",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "NO PREF" + loadPosition,
Toast.LENGTH_LONG).show();
}
// } catch (Exception e) {
// // TODO: handle exception
// Toast.makeText(getApplicationContext(), "ERROR : " + e,
// Toast.LENGTH_LONG).show();
// Log.i("ERROR", "" + e);
// e.printStackTrace();
// }
}
I am reversing , shuffling , sorting the order of my list but the application force closes. Can anybody help me with this Exception ? Can anybody also tell me how to load a list dynamically after these changes without reloading the activity or scrolling the list ?
Thanks
LOG -----------------
01-26 01:29:15.872: I/ERROR(26192): java.lang.NullPointerException
01-26 01:29:15.872: W/System.err(26192): java.lang.NullPointerException
01-26 01:29:15.882: W/System.err(26192): at java.util.Collections.reverse(Collections.java:1719)
01-26 01:29:15.882: W/System.err(26192): at com.example.allapps.AllAppsActivity.onStartPref(AllAppsActivity.java:462)
01-26 01:29:15.882: W/System.err(26192): at com.example.allpps.AllAppsActivity.onCreate(AllAppsActivity.java:252)
01-26 01:29:15.882: W/System.err(26192): at android.app.Activity.performCreate(Activity.java:5283)
01-26 01:29:15.882: W/System.err(26192): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-26 01:29:15.882: W/System.err(26192): at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 01:29:15.882: W/System.err(26192): at android.os.Looper.loop(Looper.java:136)
01-26 01:29:15.882: W/System.err(26192): at android.app.ActivityThread.main(ActivityThread.java:5001)
01-26 01:29:15.882: W/System.err(26192): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 01:29:15.882: W/System.err(26192): at java.lang.reflect.Method.invoke(Method.java:515)
01-26 01:29:15.882: W/System.err(26192): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
01-26 01:29:15.882: W/System.err(26192): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
01-26 01:29:15.882: W/System.err(26192): at dalvik.system.NativeStart.main(Native Method)
I use the methods in OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
new LoadApplications().execute();
onStartPref();
}
LoadApplication is the main method regarding the applist. I use it in OnCreate Method and the method function is below.
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager
.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(AllAppsActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(AllAppsActivity.this, null,
"Loading Please Wait...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
You seem to initialize applist in the doInBackground method of an AsyncTask. I.e. there is no guarantee that when you call onStartPref, it will be initialized.
I would suggest to call onStartPref in onPostExecute.

Android Application "Source Not Found" java.lang.runtimeexception

I switched from running my app on a phone to a nexus 10 tablet and now it says "unfortunately the application has stopped."
The tablet is running 4.4.2, my target api is set to 19 in the manifest.
When I run it in debug mode I get Source Not Found. I tried clicking edit source lookup path and adding my project and had no luck.
I've looked all over the internet and haven't had any luck solving this problem. Any suggestions would be a big help.
"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException"
Edit:
MainActivity:
package com.looper.video;
public class MainActivity extends Activity {
private VideoView video;
private MediaController ctlr;
final Uri firstVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife);
final Uri secondVideoPath = Uri.parse("android.resource://com.looper.video/" + R.raw.wildlife1);
private String videosPath = Environment.getExternalStorageDirectory() + "/videos/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File folder = new File(videosPath);
File[] customFiles = folder.listFiles();
List<String> customFileNames = new ArrayList<String>();
for(File file : customFiles) {
customFileNames.add(file.getName());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, customFileNames);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setAdapter(spinnerArrayAdapter);
video = (VideoView)findViewById(R.id.videoView1);
ctlr = new MediaController(this);
final Button firstVideoBtn = (Button) findViewById(R.id.firstVideoBtn);
firstVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playFirstVideo();
}
});
final Button secondVideoBtn = (Button) findViewById(R.id.secondVideoBtn);
secondVideoBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
playSecondVideo();
}
});
}
public void playFeatured(View v) {
try {
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
String strPath = videosPath + spinner.getSelectedItem().toString();
Toast.makeText(this, strPath, Toast.LENGTH_LONG).show();
//Uri path = Uri.parse(videosPath + spinner.getSelectedItem().toString());
video.setVideoPath(strPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public void playFirstVideo() {
video.setVideoURI(firstVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
}
public void playSecondVideo() {
SharedPreferences sp = getSharedPreferences("schedule", Context.MODE_PRIVATE);
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String startTime = sp.getString("startTime", "");
String endTime = sp.getString("endTime", "");
/*
//SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
//Date dateStartTime = parser.parse(startTime);
//Date dateEndTime = parser.parse(endTime);
Date now = new Date();
try {
if (userDate.after(ten) && userDate.before(eighteen)) {
}
} catch (ParseException e) {
// Invalid date was entered
}
System.out.println("Now:"+now);
System.out.println("Start"+startTime);
System.out.println("End:"+endTime);
//if(now.before(dateEndTime) && now.after(dateStartTime)){
//disableAll();
//} else {
*
*/
video.setVideoURI(secondVideoPath);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.requestFocus();
video.start();
video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer vmp) {
playSecondVideo();
}
});
//}
}
public void admin(View view)
{
//MySQLiteHelper db = new MySQLiteHelper(this);
//final String password = db.getUser(7).getPassword();
//db.close();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText pass = new EditText(this);
alert.setView(pass);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = pass.getText().toString().trim();
SharedPreferences sp1 = getSharedPreferences("Login", 0);
//String username = sp1.getString("UserName", "");
String password = sp1.getString("Password", "");
if(value.equals(password)) {
Intent intent = new Intent(getBaseContext(),Admin.class);
startActivity(intent);
}
//Toast.makeText(getApplicationContext(), password + " " + value, Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void disableAll(){
Button firstVideoBtn = (Button)findViewById(R.id.firstVideoBtn);
firstVideoBtn.setEnabled(false);
Button secondVideoBtn = (Button)findViewById(R.id.secondVideoBtn);
secondVideoBtn.setEnabled(false);
Spinner spinner = (Spinner)findViewById(R.id.spinnerCustomFiles);
spinner.setEnabled(false);
Button btnPlay = (Button)findViewById(R.id.btnPlayFeatured);
btnPlay.setEnabled(false);
VideoView videoView = (VideoView)findViewById(R.id.videoView1);
videoView.setEnabled(false);
}
}
Full logcat:
D/dalvikvm(2817): GC_FOR_ALLOC freed 58K, 4% free 3441K/3568K, paused 20ms, total 20ms
10-08 15:23:17.965: D/dalvikvm(2817): GC_FOR_ALLOC freed 2K, 4% free 3505K/3632K, paused 7ms, total 7ms
10-08 15:23:17.975: I/dalvikvm-heap(2817): Grow heap (frag case) to 8.739MB for 5515216-byte allocation
10-08 15:23:17.985: D/dalvikvm(2817): GC_FOR_ALLOC freed <1K, 2% free 8891K/9020K, paused 7ms, total 7ms
10-08 15:23:18.055: D/AndroidRuntime(2817): Shutting down VM
10-08 15:23:18.055: W/dalvikvm(2817): threadid=1: thread exiting with uncaught exception (group=0x4155eba8)
10-08 15:23:18.055: E/AndroidRuntime(2817): FATAL EXCEPTION: main
10-08 15:23:18.055: E/AndroidRuntime(2817): Process: com.looper.video, PID: 2817
10-08 15:23:18.055: E/AndroidRuntime(2817): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.looper.video/com.looper.video.MainActivity}: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Handler.dispatchMessage(Handler.java:102)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.os.Looper.loop(Looper.java:136)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): at java.lang.reflect.Method.invoke(Method.java:515)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-08 15:23:18.055: E/AndroidRuntime(2817): at dalvik.system.NativeStart.main(Native Method)
10-08 15:23:18.055: E/AndroidRuntime(2817): Caused by: java.lang.NullPointerException
10-08 15:23:18.055: E/AndroidRuntime(2817): at com.looper.video.MainActivity.onCreate(MainActivity.java:52)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Activity.performCreate(Activity.java:5231)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-08 15:23:18.055: E/AndroidRuntime(2817): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-08 15:23:18.055: E/AndroidRuntime(2817): ... 11 more

Android - java.lang.RuntimeException:App is crashing as soon as it launches

I am trying to send GPS coordinates to server in android, but my app is crashing as soon as i run it, i am new to android so i'm not getting how to resolve this
Here is my logcat file
01-23 14:03:40.220: E/AndroidRuntime(880): FATAL EXCEPTION: main
01-23 14:03:40.220: E/AndroidRuntime(880): Process: com.example.server2, PID: 880
01-23 14:03:40.220: E/AndroidRuntime(880): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server2/com.example.server2.MainActivity}: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-23 14:03:40.220: E/AndroidRuntime(880):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Handler.dispatchMessage(Handler.java:102)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.os.Looper.loop(Looper.java:136)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): at java.lang.reflect.Method.invoke(Method.java:515)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-23 14:03:40.220: E/AndroidRuntime(880): at dalvik.system.NativeStart.main(Native Method)
01-23 14:03:40.220: E/AndroidRuntime(880): Caused by: java.lang.IllegalArgumentException: invalid provider: null
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.checkProvider(LocationManager.java:1623)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1167)
01-23 14:03:40.220: E/AndroidRuntime(880): at com.example.server2.MainActivity.onCreate(MainActivity.java:71)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Activity.performCreate(Activity.java:5231)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-23 14:03:40.220: E/AndroidRuntime(880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
And here is my MainActivity.java:
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
String lat,lng;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://182.18.144.140:80");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onLocationChanged(Location location) {
lat = Double.toString(location.getLatitude());
lng = Double.toString (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://182.18.144.140:80");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// nameValuePairs.add(new BasicNameValuePair("android", editText1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("LAT", lat));
nameValuePairs.add(new BasicNameValuePair("LON", lng));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
}
And my manifest.xml is like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.server2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.server2.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
provider is null. You declare it here
private String provider;
but you never initialize it properly.
This line is returning null
provider = locationManager.getBestProvider(criteria, false);
which is causing your initial exception at this line
Location location = locationManager.getLastKnownLocation(provider);
you can see that by stepping back through the stacktrace.
Debug that and see why provider is null.
i can see a couple things that might have a problem here:
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
provider is null at this point, and also you need to set the permissions to get fine or coarse user location.

How to Using ArrayList and For loop after that put the loop result into an array?

I have shoreline coordinates (More than a hundred coordinates) and i want to put the coordinates in to array.
After that calculate distance between my current location to all of the coordinates (using for loop) and put the result into an array too.
So i have two array
Geo points Array
Distance Array
I want to find the minimum value of the Distance array but the program always force close. Here is my code just show ten Coordinates :
public class Nav extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
List<GeoPoint> points = new ArrayList<GeoPoint>();
Double latitude1 = Double.parseDouble("-0.696928");
Double longitude1 = Double.parseDouble("119.843473");
GeoPoint latLong1 = new GeoPoint((int)(latitude1*1e6),(int)(longitude1*1e6));
Double latitude2 = Double.parseDouble("-0.699331");
Double longitude2 = Double.parseDouble("119.84416");
GeoPoint latLong2 = new GeoPoint((int)(latitude2*1e6),(int)(longitude2*1e6));
Double latitude3 = Double.parseDouble("-0.701048");
Double longitude3 = Double.parseDouble("119.843817");
GeoPoint latLong3 = new GeoPoint((int)(latitude3*1e6),(int)(longitude3*1e6));
Double latitude4 = Double.parseDouble("-0.702592");
Double longitude4 = Double.parseDouble("119.843817");
GeoPoint latLong4 = new GeoPoint((int)(latitude4*1e6),(int)(longitude4*1e6));
Double latitude5 = Double.parseDouble("-0.701563");
Double longitude5 = Double.parseDouble("119.84622");
GeoPoint latLong5 = new GeoPoint((int)(latitude5*1e6),(int)(longitude5*1e6));
Double latitude6 = Double.parseDouble("-0.702249");
Double longitude6 = Double.parseDouble("119.84725");
GeoPoint latLong6 = new GeoPoint((int)(latitude6*1e6),(int)(longitude6*1e6));
Double latitude7 = Double.parseDouble("-0.703451");
Double longitude7= Double.parseDouble("119.846907");
GeoPoint latLong7 = new GeoPoint((int)(latitude7*1e6),(int)(longitude7*1e6));
Double latitude8 = Double.parseDouble("-0.705167");
Double longitude8 = Double.parseDouble("119.847937");
GeoPoint latLong8 = new GeoPoint((int)(latitude8*1e6),(int)(longitude8*1e6));
Double latitude9 = Double.parseDouble("-0.70654");
Double longitude9 = Double.parseDouble("119.849653");
GeoPoint latLong9 = new GeoPoint((int)(latitude9*1e6),(int)(longitude9*1e6));
Double latitude10 = Double.parseDouble("10. -0.707914");
Double longitude10 = Double.parseDouble("119.85137");
GeoPoint latLong10 = new GeoPoint((int)(latitude10*1e6),(int)(longitude10*1e6));
points.add(latLong1);
points.add(latLong2);
points.add(latLong3);
points.add(latLong4);
points.add(latLong5);
points.add(latLong6);
points.add(latLong7);
points.add(latLong8);
points.add(latLong9);
points.add(latLong10);
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
Double lat,lon;
lat = location.getLatitude ();
lon = location.getLongitude ();
Location locationA = new Location("USER");
locationA.setLatitude(lat);
locationA.setLongitude(lon);
ArrayList<Double> dist = new ArrayList<Double>();
for(int i=0; i<=points.size(); i++){
double distances = locationA.distanceTo(points(i));
dist.add(distances);
double minDist = Collections.min(dist);
Toast.makeText( getApplicationContext(),
"Your Distance to the beach is " + minDist,
Toast.LENGTH_LONG).show();
}
}
private Location points(int i) {
// TODO Auto-generated method stub
return null;
}
}
Is Somebody know what is wrong whit my code ?
And how to know and show what Goepoint is close with my location ?
Here is my LogCat
10-08 13:20:18.784: I/Process(632): Sending signal. PID: 632 SIG: 9
10-08 13:20:31.743: D/dalvikvm(675): GC_FOR_ALLOC freed 254K, 10% free 5364K/5959K, paused 95ms, total 99ms
10-08 13:20:31.993: I/Choreographer(675): Skipped 59 frames! The application may be doing too much work on its main thread.
10-08 13:20:32.024: D/gralloc_goldfish(675): Emulator without GPU emulation detected.
10-08 13:20:33.944: I/Choreographer(675): Skipped 159 frames! The application may be doing too much work on its main thread.
10-08 13:20:34.084: D/AndroidRuntime(675): Shutting down VM
10-08 13:20:34.084: W/dalvikvm(675): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-08 13:20:34.174: E/AndroidRuntime(675): FATAL EXCEPTION: main
10-08 13:20:34.174: E/AndroidRuntime(675): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.marker/com.marker.Nav}: java.lang.RuntimeException: stub
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.os.Handler.dispatchMessage(Handler.java:99)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.os.Looper.loop(Looper.java:137)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-08 13:20:34.174: E/AndroidRuntime(675): at java.lang.reflect.Method.invokeNative(Native Method)
10-08 13:20:34.174: E/AndroidRuntime(675): at java.lang.reflect.Method.invoke(Method.java:511)
10-08 13:20:34.174: E/AndroidRuntime(675): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-08 13:20:34.174: E/AndroidRuntime(675): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-08 13:20:34.174: E/AndroidRuntime(675): at dalvik.system.NativeStart.main(Native Method)
10-08 13:20:34.174: E/AndroidRuntime(675): Caused by: java.lang.RuntimeException: stub
10-08 13:20:34.174: E/AndroidRuntime(675): at com.google.android.maps.GeoPoint.(Unknown Source)
10-08 13:20:34.174: E/AndroidRuntime(675): at com.marker.Nav.onCreate(Nav.java:32)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.Activity.performCreate(Activity.java:5008)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-08 13:20:34.174: E/AndroidRuntime(675): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-08 13:20:34.174: E/AndroidRuntime(675): ... 11 more
Without seeing your error message, I can definitely spot a problem. You are iterating past the end of the list. Use < instead of <= in your loop condition.
Also, and this may not be an error, but why are you calling Collections.min() within the loop? Wouldn't you want to do that after all the distances are populated? Am I misunderstanding what you're going for?
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Use getApplicationContext().getSystemService(LOCATION_SERVICE);
or Context.getSystemService(LOCATION_SERVICE);
It Sounds like you are getting ArrayIndexOutOfBoundsException Docs
for(int i=0; i<=points.size(); i++){ // Check i<= here it should be < only
So try by changing it to
for(int i=0; i<points.size(); i++){

Categories