nullPointerException on Geocoder - java

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

Related

Android, gps. App with GPS's localizzation

I've ha problem: I 'm implementing a secondary Activity that give to me user's position. From Page1.java, through a button, open Track.java when I would like to show the coordinates of the user's location. The problem is when I click on this button: the application is closed!
This is the code of Page1.java:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
// String dato1 = getIntent().getExtras().getString("NomeDati1");
//Intent intent = getIntent(); // Point 1
// Bundle bundle = intent.getExtras(); // Point 2
// String data1 = bundle.getString("NomeDati1"); // Point 3
String dato1 = getIntent().getExtras().getString("NomeDati1"); //preleva la stringa
Toast.makeText(this, dato1, Toast.LENGTH_SHORT).show(); //PROVA: questo mi fa comparire una specie di label notifica trasparente con il valore di "data1"
Log.d("TAG", "data1:" + dato1); //credo sia una specie di debug
// String salve = getIntent().getExtras().getString("ciao");
// System.out.println("questo è il valore della prima variabile" +salve);
//FARE CONTROLLO IN CASO IL FILE XML E' VUOTO E QUINDI LA STRINGA E' VUOTA
String[] arr = dato1.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " => " + arr[i]);
}
final ArrayList <String> listp = new ArrayList<String>();
for (int i = 0; i < arr.length; ++i) {
listp.add(arr[i]);
}
// recupero la lista dal layout
final ListView mylist = (ListView) findViewById(R.id.listView1);
// creo e istruisco l'adattatore
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listp);
// inietto i dati
mylist.setAdapter(adapter);
Button b_load=(Button)findViewById(R.id.button_send2);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openTrack = new Intent(Page1.this, Track.class);
startActivity(openTrack);
}
});
}
This is the code of Track.java:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
And this is the code of the xml file associate to Track.java, called "activity_track.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="In attesa di essere localizzati..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/locationText"/>
</RelativeLayout>
This is LogCat's code:
08-08 00:04:23.801 2217-2217/com.example.giacomob.myapplication I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-08 00:04:24.035 2217-2234/com.example.giacomob.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398620, error=EGL_SUCCESS
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Root element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ ----------------------------
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ [ 08-08 00:04:25.762 2217: 2217 I/System.out ]
Current Element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Coordinata X : 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Naziome : Italia
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Paese : Cannole
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Via : Piazza San Vincenzo
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 0 => 1
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1 => 2
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 2 => Italia
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 3 => Cannole
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 4 => Piazza San Vincenzo
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa511b960, error=EGL_SUCCESS
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398900, error=EGL_SUCCESS
08-08 00:04:26.893 2217-2217/com.example.giacomob.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.giacomob.myapplication, PID: 2217
java.lang.RuntimeException: Unable to resume activity {com.example.giacomob.myapplication/com.example.giacomob.myapplication.Track}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at com.example.giacomob.myapplication.Track.onResume(Track.java:39)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is the update of Track.java
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
// private LocationManager locationManager=null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private static final int MIN_DIST = 20;
private static final int MIN_PERIOD = 30000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
// LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I don't understand the reason for witch the app is closed! Please, help me! Thanks
You never instantiate your LocationManager reference. This must be done in onCreate like this:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
The app crashes due to a Null Pointer Exception.
The answer of andrewdleach is correct; and the exact line to add in onCreate is this:
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
EDIT:
ok, try to use this
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener
{
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (locationManager == null)
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
{
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}

Android Studio. MyApp Unfortunately has stopped

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.

NullPointerException in 2 .java files

I am getting a Null Pointer Exception in my .java files and I've got no idea what I need to do to fix them.
Here is my logCat showing where the error is getting thrown.:
09-05 11:17:19.569 12588-12588/au.gov.nsw.shellharbour.saferroadsshellharbour E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.content.ContextWrapper.getSystemService(ContextWrapper.java:370)
at com.android.internal.app.AlertController$AlertParams.<init>(AlertController.java:801)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:273)
at au.gov.nsw.shellharbour.saferroadsshellharbour.GPSTracker.<init>(GPSTracker.java:116)
at au.gov.nsw.shellharbour.saferroadsshellharbour.HomeScreen$1.onClick(HomeScreen.java:30)
at android.view.View.performClick(View.java:2494)
at android.view.View$PerformClick.run(View.java:9122)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
I should point out that I'm starting out in android, having done a fair amount in iOS.
Here are my .java files
HomeScreen.java:
public class HomeScreen extends ActionBarActivity {
Button btnShowLocation;
//GPSTracker Class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
//show location button click event
btnShowLocation .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create class object
gps = new GPSTracker(HomeScreen.this); //being thrown here (line30)
if (gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n indicates new line
Toast.makeText(getApplicationContext(), "your Lcoation is - \nLat: " + latitude + "\nLon: " + longitude, Toast.LENGTH_LONG).show();
}else{
//cant get location
gps.alertDialog.show();
}
}
});
}
GPSTracker.java
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;
boolean canGetLocation = false;
Location location;
double latitude; //latitude variable
double longitude; //longitude variable
//The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MIN_TIME_BW_UPDATES = 1000;
//declare location manager
protected LocationManager locationManager;
public GPSTracker(Context context){
this.mContext = context;
getLocation();
}
//function to get latitude
public double getLatitude(){
if (location != null){
latitude = location.getLatitude();
}
//must have a return (as its a function)
return latitude;
}
public double getLongitude(){
if (location !=null){
longitude = location.getLongitude();
}
return longitude;
}
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;
//first get location from Network 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.NETWORK_PROVIDER);
if(location !=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
catch (Exception e){
e.printStackTrace();
}
return location;
}
//check if this is the best network provider
public boolean canGetLocation(){
return this.canGetLocation;
}
//show GPs settings in alert box
AlertDialog.Builder alertDialogBuilder = //also being thrown here (line 116)
new AlertDialog.Builder(this)
.setTitle("GPS is Settings")
.setMessage("GPS is not Enabled. Do you want to go to settings menu?")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivities(new Intent[]{intent});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Show the AlertDialog.
AlertDialog alertDialog = alertDialogBuilder.show();
If someone could point out what i am doing wrong, and how to fix it, it would be greatly appreciated.
I think you need to put mContext as the parameter of AlertDialog.Builder() as
new AlertDialog.Builder(mContext)

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

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo Application Crashes upon launch

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnShowLocation=null;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.btnshowloc);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \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();
}
}
});
}
This is My main activty claass
package com.example.locateus;
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.util.Log;
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
// 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) {
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();
}
}
}
}
}
} 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 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) {
// TODO Auto-generated method stub
}
#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 intent) {
// TODO Auto-generated method stub
return null;
}
}
After running the application , the application crashes upon start up, i have checked the liabaries and checking for correct build java path for the project properties , still i cannot find the solution to this . Please help me.
This code will crash:
// btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
The variable btnShowLocation will not have a value, and you must give it one.
Uncomment the line and make sure that R.id.btnShowLocation has a valid value.

Categories