native_start failed in startNavigating android GPS - android

I am new to android development. I am trying to get the Location using GPS in android. I have adopted two classes: one for the GPSTracker and the other one for the Activity. The location is getting set as null everytime and when i checked in LogCat, i get the following error:
native_start failed in startNavigating
I have set the permission in the manifest for GPS data as well. I even tried to pass fake latitude and longitude by using the emulator control, to no effect. what might be the reason? I am coding for the Android 2.3
My code is: //GPSTracker.java
public class GPSTracker extends Service implements LocationListener {
private final Context mcontext;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
double latitude,longitude;
Location location;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
protected LocationListener listener;
public GPSTracker(Context context){
this.mcontext = context;
getLocation();
}
public Location getLocation() {
try{
locationManager = (LocationManager) mcontext.getSystemService(LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location1) {
// TODO Auto-generated method stub
location = location1;
}
};
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if(isGPSEnabled){
this.canGetLocation = true;
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
Log.d("GPS", "Enabled");
if(locationManager!=null){
location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
if(location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
//Log.d("Latitude", latitude.toString());
//Log.d("Longitude", longitude.toString());
}
else{
Log.d("Location","Null");
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return location;
// TODO Auto-generated method stub
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mcontext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mcontext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// 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
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public double getLatitude() {
// TODO Auto-generated method stub
if(location!=null){
Log.d("Location",location.toString());
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
// TODO Auto-generated method stub
if(location!=null){
Log.d("Location",location.toString());
longitude = location.getLongitude();
}
return longitude;
}
}
//LocationActivity.java
public class LocationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
GPSTracker gps = new GPSTracker(LocationActivity.this);
if(gps.canGetLocation() == false){
Log.d("GPSLogFromActivity","False");
gps.showSettingsAlert();
}
else{
double latitude = gps.getLatitude();
System.out.println("Latitude: "+latitude);
double longitude = gps.getLongitude();
System.out.println("Longitud: e"+longitude);
Log.d("GPSLogFromActivity","True");
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}
}
});

hey friend have look on this
My current location always returns null. How can I fix this?

Related

android gps location listener not working in some device

I have written a GPS code using location listener for capturing latitude and longitude of a current location and it is working fine for most of my devices.
But some devices( particularly Samsung ) is not able to load this latitude longitude from location listener.
This is the code i have used continuously changing latitude and longitude.
public class MyLocationListner implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String getLatitude = "" + location.getLatitude();
String getLongitude = "" + location.getLongitude();
double x = location.getLatitude();
double y = location.getLongitude();
}
#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
}
}
To call above location listener i am using below piece of code in my activity.
emphasized text
{LocationManager location_manager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new MyLocationListner();
location_manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, listner);
}
Please give the solution why it is not working.
Thanks in advance

Remove Location Listener

I want after open dialog and click on location button, detect user's location and show user's location and then user dismiss dialog, location listener removes and not get location from onLocationChanged, I try used locationManager.removeUpdate(locListener)on override dismiss but not any chance and location after dismiss again shows! why? How can i detect user's location after show dialog and after detect location, location listener remove? Thanks
EDIT:
public class DialogTest extends Dialog implements
android.view.View.OnClickListener {
Context context;
LocationManager locationManager;
LocationListener locationListener;
Location location;
public DialogTest(Context context) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.context = context;
setContentView(R.layout.profile_dialog);
getWindow().setBackgroundDrawableResource(R.drawable.background_dialog);
firstAccessLocation=true;
setCancelable(true);
initialize();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
findAddress();
}
private void findAddress() {
// if (gpsCheckBox.isChecked()) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// }
}
private void stopTracking(){
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
#Override
public void dismiss() {
// TODO Auto-generated method stub
stopTracking();
gpsTurnOff();
super.dismiss();
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(location!=null)
Log.e("location", location.getLatitude()+"");
location = loc;
if (location != null&& firstAccessLocation) {
setAddress(location.getLatitude(), location.getLongitude());
firstAccessLocation=false;
}
Toast.makeText(context, "changed", Toast.LENGTH_LONG).show();
Log.e("location", "changed");
}
#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
}
}
}
In new code you should use LocationClient rather then LocationManager. It's more efficient in getting the location with minimal energy(battery drain) with greater accuracy. Look here LocationClient vs LocationManager. With LocationClient established you can call getLastLocation() which provide you last location and doesn't start cyclic location updates.
If you want to stick with LocationManager use requestSingleUpdate (String provider, LocationListener listener, Looper looper) method to get only one newest location from it.

Android: Not able to store location in SharedPreference

Here, I'm using the current location of the user as well as the a location which is stored previously and showing path between them.
I'm able to get the correct current location but the location I'm trying to store permanently in Shared Preferences are just getting stored until application is running. Once the application is removed and opened again the saved location gets initialised back to 0.0.
I want to store latitude and longitude permanently once after user press save/change location button.
Here's the code:
public class Fragment_ReachHome extends Fragment {
WebView wv;
ProgressDialog pg;
Background bg;
AlertDialog.Builder alert;
ConnectionDetector cd;
MediaPlayer exceptionNotifier;
boolean isInternetPresent = false;
LocationManager locationManager;
LocationListener locationListener;
float latitude;
float longitude;
Location loc;
public static float savelati, savelongi;
Boolean islocationmanagerrequested = false;
Button bsaveorchangeloc, bshowsavedloc;
SharedPreferences pref;
SharedPreferences.Editor edit;
Boolean islocsaved = false, isbpressed = false;
public Fragment_ReachHome() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reach_home, container, false);
wv=(WebView)rootView.findViewById(R.id.webView1);
alert = new AlertDialog.Builder(getActivity());
cd = new ConnectionDetector(getActivity());
locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
Toast.makeText(getActivity(), "Loading... Please Wait..", Toast.LENGTH_LONG).show();
locationListener = new LocationListener() { //-----X0-- THIS SHOULD ALWAYS COME FIRST THEN X1 SHOULD BE WRITTEN
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
latitude = Float.valueOf((float) loc.getLatitude());
longitude = Float.valueOf((float) loc.getLongitude());
if(isbpressed){
Toast.makeText(getActivity(), "on loc change", Toast.LENGTH_LONG).show();
}
bg = new Background();
bg.execute();
}
};
try {
isInternetPresent = cd.isConnectingToInternet();
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
}
if(isInternetPresent){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListener);
}else{
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Internet Not Present..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
pref = this.getActivity().getSharedPreferences("", 0);
edit=pref.edit();
bsaveorchangeloc =(Button)rootView.findViewById(R.id.button1);
bshowsavedloc =(Button)rootView.findViewById(R.id.button2);
islocsaved = pref.getBoolean("locsaved", false);
bsaveorchangeloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
progress();
try {
isInternetPresent = cd.isConnectingToInternet();
} catch (Exception e) {
Toast.makeText(getActivity(), e.toString(),
Toast.LENGTH_LONG).show();
}
if(isInternetPresent){
//ONLY AFTER X0 THIS MUST BE WRITTEN
Toast.makeText(getActivity(), "Saving Location!!", Toast.LENGTH_LONG).show();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListener);
isbpressed = true;
islocationmanagerrequested = true;
savelati = pref.getFloat("latestlati", Float.valueOf((float) loc.getLatitude())); //giving default value as 0
savelongi= pref.getFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", true);
edit.commit();
if(islocationmanagerrequested){
locationManager.removeUpdates(locationListener);
}
pg.dismiss();
}else{
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Internet Not Present..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
}
});
bshowsavedloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), savelati+","+savelongi, Toast.LENGTH_LONG).show();
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.setWebViewClient(new MyWebClient());
return rootView;
}
public void progress(){
pg = new ProgressDialog(getActivity());
pg.setTitle("");
pg.setMessage("Please Wait.........");
pg.setCancelable(false);
pg.setIndeterminate(true);
pg.show();
}
class Background extends AsyncTask<Void, Void, Void>
{
#SuppressLint("SetJavaScriptEnabled")
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try{
if(islocsaved){
wv.loadUrl("http://maps.google.com/maps?saddr="+savelati+","+savelongi+"&daddr="+loc.getLatitude()+","+loc.getLongitude());
}else{
pg.dismiss();
exceptionNotifier = MediaPlayer.create(getActivity(), R.raw.notify);
exceptionNotifier.start();
alert.setTitle("Alert!");
alert.setMessage("Your home location is not saved yet..! ");
alert.setCancelable(true);
alert.setPositiveButton("Ok!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
exceptionNotifier.release();
}
}).show();
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getActivity(), latitude+","+longitude, Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
}
#Override
protected void onPreExecute() {
progress();
}
}
public class MyWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pg.dismiss();
}
}
}
Please let me know the correct changes in the code to get store the location permanently...
You can saved value in preference on onPause() or any Button click event where you want using below code.
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", true);
edit.commit();
You can get saved value from preference on onResume() using below code.
savelati = pref.getFloat("latestlati", 0.0);
savelongi= pref.getFloat("latestlongi", 0.0);
islocsaved=edit.getBoolean("locsaved", true);
and for more information go to Android Shared preferences example or http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
You need to save the value of longitide and latitude first in the shareprefrences.
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude());
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLongitude);
For the better suggestion you have to take your SharedPreferance instance globally
then in your onLocationChanged(Location location) change method you can do this code
edit.putFloat("latestlati", Float.valueOf((float) loc.getLatitude()))
edit.putFloat("latestlongi", Float.valueOf((float) loc.getLatitude()));
edit.putBoolean("locsaved", false);
edit.commit();
So, that every location change your value for the location is updated and after come to your activity you always get the refresh/latest value.
with onCreate() or onResume() you can get the
savelati = pref.getFloat("latestlati", 0.0);
savelongi= pref.getFloat("latestlongi", 0.0);
islocsaved=edit.getBoolean("locsaved", false);

Retrieve GPS location using android

I'm trying to get gps location of the current location using simple android program. I used onLocationChanged() method for this. But it returning the coordinates as 0.0. The users permission part is correct. This is the code of main one.
public class MainActivity extends Activity {
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
final TextView tv = (TextView) findViewById(R.id.textView1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gps = new GPSTracker(MainActivity.this);
double lat = gps.latitude;
String mlat = String.valueOf(lat);
tv.setText(mlat);
}
});
}
}
this is the gps location class that im using...
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longtitude;
protected LocationManager locationManager;
public GPSTracker(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation(){
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return null;
}
protected void onStart() {
}
protected void onPause(){
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

How to send updated long/lat to server in android?

In my application i want to get the updated location of the mobile user and i want to send it to the server continuously after periodic interval of certain time or after the user travels certain(say 500 meter) distance.I need these things to be done in backgroung.I know for this i have to implement service class. But I am not getting exactly how to do this.I did some work on that.
Can anybody please help me in this issue.
I did following things in the service class.
public class BackGroundService extends Service implements LocationListener{
public static final String Tag = BackGroundService.class.getName();
LocationManager myLocationManager;
Location myLocation;
LocationListener myLocationListener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void OnCreate()
{
super.onCreate();
Log.d(Tag, "Service Started");
android.os.Debug.waitForDebugger();
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_LOW);
String locationProvider = myLocationManager.getBestProvider(criteria, true);
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 500, myLocationListener);
myLocation = myLocationManager.getLastKnownLocation(locationProvider);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
longitude = location.getLongitude();
latitude = location.getLatitude();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Provider is disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Location Provider is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
From here I want know how can i get current lat/long of user and send it to the server.
Answer for my question is.......
public class LocationService extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final LocationManager mlocmag = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener mlocList = new MyLocationList();
final Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
UpdateWithNewLocation(loc); // This method is used to get updated location.
mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocList);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
private void UpdateWithNewLocation(final Location loc) {
// TODO Auto-generated method stub
if(loc!= null)
{
final double lat =loc.getLatitude(); // Updated lat
final double Long = loc.getLongitude(); // Updated long
ConnectMySQL obj = new ConnectMySQL();
obj.call(lat,Long); // Call this method when location is updated and save the data.
}
else
{
String latLongStr = "No lat and longitude found";
Toast.makeText(this, "Your location is "+latLongStr ,Toast.LENGTH_LONG).show();
}
}
public class MyLocationList implements LocationListener
{
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
UpdateWithNewLocation(arg0);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS Disable ", Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS enabled", Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Categories

Resources