2014-09-05 1 views
1

Я получаю исключение Null Pointer в моих .java-файлах, и я не знаю, что мне нужно сделать, чтобы исправить их.NullPointerException в 2 .java-файлах

Вот мой LogCat показ, где становится брошена ошибка .:

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) 

Я должен отметить, что я начинаю в андроиде, сделав изрядное количество в прошивке.

Вот мои .java файлы

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

Если кто-то может указать на то, что я делаю не так, и как это исправить это, было бы весьма полезно.

+2

Это не выглядит как полный трассировки стека. Пожалуйста, опубликуйте остальную часть. – Rob

+0

Что произойдет, если вы замените 'HomeScreen.this'' getActivity() '? – ChiaraHsieh

+0

Или 'getApplicationContext()' в этом случае? – ChiaraHsieh

ответ

0

Я думаю, вам нужно поставить mContext в качестве параметра AlertDialog.Builder() в

new AlertDialog.Builder(mContext) 
Смежные вопросы