Android Studio. MyApp Unfortunately has stopped - java

I am trying to get the current location (latitude and longtitude) and my app is not running. I have a TextView to view the longtitude (testing for a start).
This is my mainActivity code:
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.ViewUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
//public Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView);
//creating new object of the method
MyLocationListener myLocationListener = new MyLocationListener();
double longt=myLocationListener.getLocation().getLongitude();
String longi =String.valueOf(longt);
//String lat1 =String.valueOf(lat);
tv.setText(longi);
//myLocationListener.onProviderEnabled(WIFI_SERVICE);
//myLocationListener.onProviderDisabled(WIFI_SERVICE);
// myLocationListener.getLatitude(location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void process(View view){
Intent intent;
intent = new Intent(this,MapsActivity.class);
startActivity(intent);
}
}
and these errors came up:
>
8585-8585/com.example.maxi.try_v2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.maxi.try_v2, PID: 8585
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.maxi.try_v2/com.example.maxi.try_v2.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.maxi.try_v2.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
if you can help, I would be glad.
this is the MyLocationListener class (sorry for the incomplete info)
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Created by maxi on 7/17/15.
*/
public class MyLocationListener implements LocationListener {
private Context mContext;
//gps status flag
boolean isGpsEnabled = false;
boolean canGetLocation = false;
//flag for network status
boolean isNetworkEnabled;
//min distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
//min time between updates in miliseconds
private static final long MIN_TIME_BW_UPDATES = 60000; //1min
protected LocationManager locationManager;
public static double latitude;
public static double longtitude;
Location location;
/* public MyLocationListener(Context context){
this.mContext = context;
getLocation();
}*/
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longtitude = loc.getLongitude();
}
public void getLatitude(Location loc) {
latitude = loc.getLatitude();
String lat = String.valueOf(latitude);
Log.w("poutsa", lat);
}
public void onProviderDisabled(String provider) {
Log.w("myApp", "no network");
}
public void onProviderEnabled(String provider) {
Log.w("myApp", "NetIsOn");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//http://developer.android.com/reference/android/location/LocationListener
// .html#onStatusChanged%28java.lang.String,%20int,%20android.os.Bundle%29
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//gettin GPS status
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//gettin network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
//no network
} else {
this.canGetLocation = true;
//first get location from provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
if (isGpsEnabled){
if (location == null){
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Gps Enabled","Gps Enabled");
if (locationManager != null){
location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return location;
}
}

This is giving you a NullPointerException, which means you're getting null when making a request to the Location
double longt=myLocationListener.getLocation().getLongitude();

Caused by: java.lang.NullPointerException
at com.example.maxi.try_v2.MainActivity.onCreate(MainActivity.java:27)
Open MainActivity.java, look at line 27: you have a null variable.
Since you did not tell what line 27 is, I cannot help any more.
Just check for nulls, for example: myLocationListener.getLocation() might be null in your code.

Related

How to get users location using a class in android getting null pointer exception

I am using a separate class to get user's location. How to get user's location by calling interface in my activity.I cant understand How can i get user's location' latitude and longitude in my activity? It is giving me null pointer exception when i create object of class and call method
My Activity
public class missingPerson extends AppCompatActivity implements OnLocationUpdateListener {
OnLocationUpdateListener lu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_missing_person);
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
locationHandler.getDeviceLocation();
}
#Override
public void onLocationChanged(Location location) {
Location location1 = location;
String latitute = String.valueOf(location1.getLatitude());
Log.i("No Result", latitute);
}
#Override
public void onError(String error) {
}
}
Class for location
package com.example.fizatanveerkhan.citycops;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.List;
public class LocationHandler {
private Activity activity;
private FusedLocationProviderClient mFusedLocationProviderClient;
private Location mLastKnownLocation;
private LocationCallback mLocationCallback;
private LocationRequest mLocationRequest;
private OnLocationUpdateListener onLocationUpdateListener;
private boolean updateStartedInternally = false;
private boolean isconnected = false;
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
this.activity = activity;
this.onLocationUpdateListener = onLocationUpdateListener;
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity);
createLocationRequest();
getDeviceLocation();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
mLastKnownLocation = location;
if (onLocationUpdateListener != null) {
onLocationUpdateListener.onLocationChanged(location);
if(updateStartedInternally){
stopLocationUpdate();
}
}
}
}
};
}
public boolean isConnected() {
return isconnected;
}
public void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(activity, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
isconnected = true;
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastKnownLocation = (Location) task.getResult();
if (mLastKnownLocation == null) {
updateStartedInternally = true;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else if (mLastKnownLocation != null){
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// This message appears in logcat with latitute still it say that
// onLocationUpdateListener.onLocationChanged is invoked on null object
// reference
Log.e("Location", String.valueOf(mLastKnownLocation.getLatitude()));
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
}
}
else {
onLocationUpdateListener.onError("Can't get Location");
}
}
}) ;
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
onLocationUpdateListener.onError(e.getMessage());
}
}
public void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
updateStartedInternally = false;
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private void stopLocationUpdate() {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
//other new Methods but not using right now..
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);//set the interval in which you want to get locations
mLocationRequest.setFastestInterval(5000);//if a location is available sooner you can get it (i.e. another app is using the location services)
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
And this is Interface
import android.location.Location;
public interface OnLocationUpdateListener {
void onLocationChanged(Location location);
void onError(String error)
}
Error
I/AssistStructure: Flattened final assist data: 4848 bytes, containing 1 windows, 15 views
E/Location: 37.4219983
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fizatanveerkhan.citycops, PID: 14006
java.lang.NullPointerException: Attempt to invoke interface method 'void
com.example.fizatanveerkhan
.citycops.OnLocationUpdateListener.onLocationChanged
(android.location.Location)' on a null object reference
at com.example.fizatanveerkhan.citycops.
LocationHandler$2.onComplete(LocationHandler.java:88)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os
.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 14006 SIG: 9
Application terminated.
final LocationHandler locationHandler = new LocationHandler(missingPerson.this,lu);
What is this "lu" that you pass as second argument during instance? I don't see it anywhere.
public LocationHandler(Activity activity, final OnLocationUpdateListener onLocationUpdateListener) {
//........
}
LocationHandler take OnLocationUpdateListener and set
this.onLocationUpdateListener = onLocationUpdateListener;
Then, you call
onLocationUpdateListener.onLocationChanged(mLastKnownLocation);
If you pass "lu" (that maybe is null), is pretty clear that object's onLocationUpdateListener is null.

Latitude and Longitude are null

I'm working on an app getting user's current location and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main
Process: io.xgear.geotag, PID: 29286
java.lang.NullPointerException
at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
this is the piece of code for getting latitude and longitude to send
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
and this is the full code
package io.xgear.geotag;
import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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 boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
if( location != null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
}
inside GeoTagTask location object is different one and also doesn't initilized.
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());

Q. Android GPS location

I'm trying to access my GPS location of my device, so I can then use this to load Google maps on the user's coordinates. I have followed various guides, but I dont seem to be acquiring any correct values.
The app does not crash, it simply displays a zero
Here is the code for my maps activity:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class Maps extends ActionBarActivity {
Button btnLocation;
GPSTracker gps;
//private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide action bar before Activity load
getSupportActionBar().hide();
setContentView(R.layout.activity_maps);
btnLocation = (Button) findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(Maps.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(),
"Your location is -\nLat: " + latitude +
"\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
}
});
Below is my code that is meant to obtain the location
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private final Context context;
//Flags for network/gps status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
public LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation(){
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
//For use over networks
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
//For use over GPS
if (isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e ) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
} else {
getLocation();
}
return latitude;
}
public double getLongitude() {
if (location != null){
longitude = location.getLongitude();
} else {
getLocation();
}
return longitude;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is being set");
alertDialog.setMessage("GPS is not enabled. Go to settings.");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public boolean canGetLocation() {
return this.canGetLocation;
}
I have also included the necessary code into the manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Help is greatly appreciated
DO NOT USE GPSTracker!!!! Dear god this code will not die. Its horrible, bad, awful code. I have a blog post at http://gabesechansoftware.com/location-tracking/ showing the dozen different ways that code is flawed. I also have a much better implementation available there. That code was written by someone who didn't fully understand location tracking, and it makes a lot of bad assumptions.
If I was allowed to delete one class from this website it would be all mentions of that one. Its just horribly naive code.

geocoder declaration null pointer exception in service class

when i put reverse geocoder function into service class and trying to call in activity ,, i got null pointer exception ..
this is my class
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String tempAddress;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
location = locationManager
.getLastKnownLocation(locationProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
String locationgps=LocationManager.GPS_PROVIDER;
location = locationManager
.getLastKnownLocation(locationgps);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS/Data roaming is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
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 location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
double latitude=getLatitude();
double longitude=getLongitude();
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
Toast.makeText(getApplicationContext(),"I am at: "+strAddress.toString(),Toast.LENGTH_LONG).show();
// myAddress.setText("I am at: " +strAddress.toString());
tempAddress=strAddress.toString();
return tempAddress;
//Intent intent = new Intent("MyCustomIntent");
// add data to the Intent
// intent.putExtra("strAddress",strAddress.toString());
// intent.setAction("android.provider.Telephony.SMS_RECEIVED");
// sendBroadcast(intent);
// Intent intent = new Intent (Menu.this,IncomingSms.class);
// intent.putExtra("strAddress",strAddress.toString());
// sendBroadcast(intent);
}
else
Toast.makeText(getApplicationContext(), "No Location found", Toast.LENGTH_LONG).show();
//myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Tidak bisa Menerima Alamat ,, harap cek jaringan dan gps hp anda!", Toast.LENGTH_LONG).show();
showSettingsAlert();}
tempAddress="Could not Retrive Address!";
return tempAddress;
}
}
and this is my activity class:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import javax.xml.transform.Templates;
import mo.locationtracking.GPSTracker;
import mo.sms.IncomingSms;
import info.MonitoringObjek.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Menu extends Activity implements OnClickListener{
private Button bTambah;
private Button bLihat;
//private Button blokasi;
GPSTracker gps;
private TextView myAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
myAddress = (TextView)findViewById(info.MonitoringObjek.R.id.lokasisekarang);
// blokasi=(Button) findViewById(R.id.button_lokasi);
// blokasi.setOnClickListener(this);
bTambah = (Button) findViewById(R.id.button_tambah);
bTambah.setOnClickListener(this);
bLihat = (Button) findViewById(R.id.button_view);
bLihat.setOnClickListener(this);
// create class object
gps = new GPSTracker(Menu.this);
// check if GPS enabled
if(gps.canGetLocation()){
//double latitude = gps.getLatitude();
//double longitude = gps.getLongitude();
//Geocoder geocoder;
//myAddress.setText("Latitude: "+latitude+"Longitude: "+longitude);
String tempAddress=gps.getMyLocationAddress();
myAddress.setText("I am at: " +tempAddress);
gps.stopUsingGPS();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button_tambah :
Intent i = new Intent(this, CreateData.class);
startActivity(i);
break;
case R.id.button_view :
Intent i2 = new Intent(this, ViewData.class);
startActivity(i2);
break;
}
}
}
and this is my logcat:
05-28 14:47:14.187: E/Trace(5031): error opening trace file: No such file or directory (2)
05-28 14:47:14.688: E/AndroidRuntime(5031): FATAL EXCEPTION: main
05-28 14:47:14.688: E/AndroidRuntime(5031): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.MonitoringObjek/mo.database.Menu}: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.access$600(ActivityThread.java:137)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Handler.dispatchMessage(Handler.java:99)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Looper.loop(Looper.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.main(ActivityThread.java:4786)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invoke(Method.java:511)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
05-28 14:47:14.688: E/AndroidRuntime(5031): at dalvik.system.NativeStart.main(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): Caused by: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.Geocoder.<init>(Geocoder.java:83)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.locationtracking.GPSTracker.getMyLocationAddress(GPSTracker.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.database.Menu.onCreate(Menu.java:54)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Activity.performCreate(Activity.java:5008)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
05-28 14:47:14.688: E/AndroidRuntime(5031): ... 11 more
i see inthis post it's say geocoder must declare inside on create in activity .. is that impossible to declare in service class? i need that geocoder still update even my application is closed..
The Location from the android application is not that much accurate you can call the google api webservice using get method and parse the json result and you can get Area Block city street etc
it is more accurate than default one

nullPointerException on Geocoder

I am playing around with working with the location but now i keep on getting a nullPointerException when ever i click the button on the app. The button refreshes the location which is displayed. The location is displayed in latitude,longitude, street address,city,country and postal address. here is the code below.
package com.example.metrorails;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
CurrentPosition currentPosition;
String address;
String city;
String country;
String postalCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button refresh;
refresh = (Button)findViewById(R.id.refresh);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentPosition = new CurrentPosition(MainActivity.this);
TextView showresults = (TextView) findViewById(R.id.show_results);
showresults.setTextSize(20);
if(currentPosition.canGetLocation()){
double latitude = currentPosition.getLatitude();
double longitude = currentPosition.getLongitude();
showresults.setText("current latitude: "+latitude +"\n current longitude: "+longitude+
"\n Address is: " +currentPosition.getAddress() + "\n city is: "+currentPosition.getCity()+
"\n Current Country is: "+currentPosition.getCountry() +"\n Area Code : "+currentPosition.getPostalCode());
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
currentPosition.showSettingsAlert();
}
}
});
}
#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;
}
}
I'm still having problems with this program. here is the logcat below.
09-09 18:56:52.393: E/AndroidRuntime(1882): FATAL EXCEPTION: main
09-09 18:56:52.393: E/AndroidRuntime(1882): java.lang.NullPointerException
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.GeocoderParams. <init>(GeocoderParams.java:50)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.Geocoder.<init>(Geocoder.java:83)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.CurrentPosition.<init>(CurrentPosition.java:71)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.MainActivity$1.onClick(MainActivity.java:31)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View.performClick(View.java:4240)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View$PerformClick.run(View.java:17721)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.handleCallback(Handler.java:730)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Looper.loop(Looper.java:137)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invoke(Method.java:525)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 18:56:52.393: E/AndroidRuntime(1882): at dalvik.system.NativeStart.main(Native Method)
09-09 18:57:01.512: I/Process(1882): Sending signal. PID: 1882 SIG: 9
below is the CurrentPosition class.
package com.example.metrorails;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class CurrentPosition extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public static String address;
public static String city;
private static String country;
private static String postalCode;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public String getAddress(){
return address;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public String getPostalCode(){
return postalCode;
}
public CurrentPosition(Context context) {
this.mContext = context;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocode = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocode.getFromLocation(latitude,longitude, 1);
this.address = addresses.get(0).getAddressLine(0);
this.city = addresses.get(0).getAddressLine(1);
this.country = addresses.get(0).getAddressLine(2);
this.postalCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}} catch (Exception e) {
e.printStackTrace();
}
this.location = location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(CurrentPosition.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
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 location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}

Categories