Android: Not able to store location in SharedPreference - android

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);

Related

How to call a webservice continuously in every seconds?

allVehiclesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String item=allVehiclesSpinner.getItemAtPosition(position).toString();
if(!item.equalsIgnoreCase("Select")){
position=0;
vdetails.vehicleNo = item;
dbhHelper.opendatabase();
vdetails=dbhHelper.getVehicleId(item);
dbhHelper.close();
getLiveTrackingsAsyncTask livetask=new getLiveTrackingsAsyncTask();
livetask.execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public class getLiveTrackingsAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(VTS_LiveTracking.this);
Dialog.setMessage(VTS_LiveTracking.this.getResources().getString(
R.string.loading));
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
Dialog.setContentView(R.layout.progress);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result="";
Log.d(WebServiceHelper.TAG, "AsyncTask>>>>>>>>>>>");
if(isInternetPresent){
try {
Log.d(WebServiceHelper.TAG, "AsyncTask CHeck Internet>>>>>>>>>>>");
Log.d(WebServiceHelper.TAG, "VehicleId CHeck Internet>>>>>>>>>>>"+vdetails.vehicleId);
vd=WebServiceHelper.getLiveTrackingDetails(ClientCode, SecretCode, vdetails.vehicleId);
//vd=WebServiceHelper.getLiveTrackingDetails(ClientCode, SecretCode, "2");
Log.d(WebServiceHelper.TAG, "VD>>>>>>>>"+vd.length);
for(int i=0;i<vd.length;i++){
Log.d(WebServiceHelper.TAG, "LiveTrackingElements1>>>>>>>>>>>>>>"+vd[i].deviceMobNo);
Log.d(WebServiceHelper.TAG, "LiveTrackingElements2>>>>>>>>>>>>>>"+vd[i].driverName);
vdetails.latitude=vd[i].latitude;
vdetails.longitude=vd[i].longitude;
Log.d(WebServiceHelper.TAG, "vdetails.latitudeLiveTrackingElements1>>>>>>>>>>>>>>"+vdetails.latitude);
Log.d(WebServiceHelper.TAG, "vdetails.longitudeLiveTrackingElements2>>>>>>>>>>>>>>"+vdetails.longitude);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result="Success";
}else{
result="Failure";
}
return result;
}
#Override
protected void onPostExecute(String result) {
if(result.contentEquals("Success")){
Log.d(WebServiceHelper.TAG, "AsyncTaskonPostExecute>>>>>>>>>>>");
Log.d(WebServiceHelper.TAG, "statuslogin>>>>>>>>>>>"+vdetails.status_login);
if(vdetails.status_login.equals("success")){
String lat=vdetails.latitude;
String lon=vdetails.longitude;
latitude=Double.parseDouble(vdetails.latitude);
longitude=Double.parseDouble(vdetails.longitude);
Log.d(WebServiceHelper.TAG, "latitude>>>>"+vdetails.latitude);
Log.d(WebServiceHelper.TAG,"longitude>>>>"+vdetails.longitude);
latlng=new LatLng(latitude, longitude);
Marker m=map.addMarker(new MarkerOptions().position(latlng));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15.0f));
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final Dialog dialog = new Dialog(VTS_LiveTracking.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Report");
TextView driver, speed,latitude,longitude,last_updated_time,gps_status,
driver_mobile_no,vehicle_idle_status,ac_status,device_mobile_no,engine_status;
driver = (TextView)dialog.findViewById(R.id.drivernametxt);
speed=(TextView)dialog.findViewById(R.id.speedvaluetxt);
latitude=(TextView)dialog.findViewById(R.id.latitudetxt);
longitude=(TextView)dialog.findViewById(R.id.longitudetxt);
last_updated_time=(TextView)dialog.findViewById(R.id.last_updated_timetxt);
gps_status=(TextView)dialog.findViewById(R.id.gps_statustxt);
driver_mobile_no=(TextView)dialog.findViewById(R.id.driver_mobile_notxt);
vehicle_idle_status=(TextView)dialog.findViewById(R.id.vehicle_idle_statustxt);
ac_status=(TextView)dialog. findViewById(R.id.ac_statustxt);
device_mobile_no=(TextView)dialog.findViewById(R.id.device_mobile_notxt);
engine_status=(TextView)dialog.findViewById(R.id.engine_statustxt);
driver.setText(vdetails.driverName);
speed.setText(vdetails.vehicleSpeed);
latitude.setText(vdetails.latitude);
longitude.setText(vdetails.longitude);
last_updated_time.setText(vdetails.lastUpdatedDateTime);
gps_status.setText(vdetails.gpsStatus);
driver_mobile_no.setText(vdetails.driverMobNo);
vehicle_idle_status.setText(vdetails.vehicleIdleStatus);
ac_status.setText(vdetails.acStatus);
device_mobile_no.setText(vdetails.deviceMobNo);
engine_status.setText(vdetails.engineStatus);
dialog.show();
Button cancel=(Button) dialog.findViewById(R.id.okbtn);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return false;
}
});
}else{
Toast.makeText(getApplicationContext(), vdetails.failReason, Toast.LENGTH_LONG).show();
}
}else if(result.contentEquals("Failure")){
Toast.makeText(getApplicationContext(), "Error in Login", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
Dialog.dismiss();
Dialog=null;
}
}
}
Hi,
For my app,It is very necessary to display the location of a vehicle at a particular location.The location of the vehicle is given by the json webservices.Also the vehicle is moving and location is updated by the webservice.But according to my code the vehicle is not moving.How can I implement the movement of vehicle in my app?How can I implement the location change using timer?Is there any other methods to implement this?
Please help me
Here is my code
Use Timer..
mytimer = new Timer();
final TimerTask mytask = new TimerTask() {
public void run() {
//your code here
}
});
mytimer.scheduleAtFixedRate(mytask, int delay, int time);
Class To Start Service
allVehiclesSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String item=allVehiclesSpinner.getItemAtPosition(position).toString();
if(!item.equalsIgnoreCase("Select")){
position=0;
vdetails.vehicleNo = item;
dbhHelper.opendatabase();
vdetails=dbhHelper.getVehicleId(item);
dbhHelper.close();
Intent intent = new Intent(A.this,
Service_A.class);
startService(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
USE SERVICE TO UPDATE WEBSERVICE AFTER 1 SEC
Service_ A extend service
{
private Handler handler = new Handler();
#Override
public void run() {
// TODO Auto-generated method stub
handler.postDelayed(Service_ A.this,1000);
}
//do you code
}
Try to use thread to invoke async task every second use below code to replace
getLiveTrackingsAsyncTask livetask=new getLiveTrackingsAsyncTask();
livetask.execute();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1 * 1000);
new getLiveTrackingsAsyncTask.execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();

Updating Activity with Latitude/Longitude values returned from a Service

I'm trying to write a simple app that updates the MainActivity with the Lat/Lng values returned by the service. But it always returns the null value. I have added permissions and added TheService.java as service in AndroidManifest.xml file...Kindly tell me where I have gone wrong.
MainActivity.java
public class MainActivity extends Activity {
TextView tv1, tv2;
IntentFilter filter;
receive rec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
filter = new IntentFilter("Updated");
rec = new receive();
Intent gps_int = new Intent(this,TheService.class);
startService(gps_int);
}
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(rec);
}
#Override
public void onResume()
{
super.onResume();
rec = new receive();
registerReceiver(rec, filter);
}
#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;
}
public class receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
tv1.setText(intent.getExtras().getString("lat"));
tv2.setText(intent.getExtras().getString("lon"));
Toast.makeText(getApplicationContext(), "Toast Executed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "BR Latitude "+intent.getExtras().getString("lat"),Toast.LENGTH_SHORT).show();
}
}}
TheService.java
public class TheService extends Service implements LocationListener {
LocationManager lm;
Location loc;
double lat = 0;
double lon = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
lm=(LocationManager)getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(loc);
return START_STICKY;
}
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateui(location);
}
private void updateui(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent gps_intent = new Intent("Updated");
gps_intent.putExtra("lat", lat);
gps_intent.putExtra("lon", lon);
sendBroadcast(gps_intent);
}
#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
}}
You should use the Google Play Services for the location, that's easier to handle.
What for do you even need a Service? Having a location listener in your Activity is totally fine.
If you want to stay with the Service, than bind the Activity to it, instead of using a Broadcast.

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;
}
}

native_start failed in startNavigating android GPS

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?

Loading Map crashes on few devices

I have a listview and onItemSelected, will call an Activity to get user location (his current lat and lng), this activity has no layout, then this activity automatically calls another activity which gets lat and lng of the item selected from the listview and marks both the user location and item location on the map.
This worked fine when I was testing on Emulator and Samsung Galaxy Ace, But it crashes when I'm testing on Micromax A50 and Sony Xperia.
Sad thing is that I can't install drivers of the later 2 devices, so I cant get logcat.
Can any 1 guess what might have gone wrong??
My code for finding user location is:
public class MyLocationActivity extends Activity implements LocationListener {
private LocationManager mgr;
private String best;
public static double myLocationLatitude;
public static double myLocationLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
Log.d("best provider", best);
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
/*Intent intent = new Intent(MyLocationActivity.this, ShowMapActivity.class);
startActivity(intent);*/
Intent intent = new Intent(MyLocationActivity.this, MapMarkerActivity.class);
startActivity(intent);
finish();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mgr.removeUpdates(this);
}
#Override
protected void onResume() {
super.onResume();
mgr.requestLocationUpdates(best, 15000, 1, this);
}
private void dumpLocation(Location l) {
if (l == null) {
myLocationLatitude = 0.0;
myLocationLongitude = 0.0;
} else {
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String p : providers) {
dumpProviders(p);
}
}
private void dumpProviders(String s) {
LocationProvider info = mgr.getProvider(s);
StringBuilder builder = new StringBuilder();
builder.append("name: ").append(info.getName());
}
}
and item location is:
public class MapMarkerActivity extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
private Drawable marker1;
private Drawable marker2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular_entry);
Button feedButton = (Button) findViewById(R.id.feedButton_particularEntry);
feedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MapMarkerActivity.this,
FeedListViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
});
Button iWantButton = (Button) findViewById(R.id.iWantButton_particularEntry);
iWantButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
IWantActivity.class);
startActivity(intent);
}
});
Button shareButton = (Button) findViewById(R.id.shareButton_particularEntry);
shareButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ShareActivity.class);
startActivity(intent);
}
});
Button profileButton = (Button) findViewById(R.id.profileButton_particularEntry);
profileButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapMarkerActivity.this,
ProfileActivity.class);
startActivity(intent);
}
});
map = (MapView) findViewById(R.id.map);
map.getController().setCenter(
getPoint(FeedListViewActivity.lat, FeedListViewActivity.lng));
map.getController().setZoom(13);
map.setBuiltInZoomControls(true);
marker1 = getResources().getDrawable(R.drawable.marker2);
marker2 = getResources().getDrawable(R.drawable.marker1);
marker1.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
marker2.setBounds(0, 0, marker1.getIntrinsicWidth(),
marker1.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker1));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return (true);
} else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return (true);
}
return (super.onKeyDown(keyCode, event));
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
public class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker) {
super(marker);
boundCenterBottom(marker);
OverlayItem oli1 = new OverlayItem(getPoint(
MyLocationActivity.myLocationLatitude,
MyLocationActivity.myLocationLongitude), "YL",
"Your Location");
oli1.setMarker(marker2);
items.add(oli1);
OverlayItem oli2 = new OverlayItem(getPoint(
FeedListViewActivity.lat, FeedListViewActivity.lng), "SL",
"Store Location");
oli2.setMarker(marker1);
items.add(oli2);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
Toast.makeText(MapMarkerActivity.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}
Maybe this can help you:
Location Method Calls Crashes On Some Devices

Categories

Resources