I'm a noob to Android (and not too hot on Java either).
I am trying to make sure GPS & internet are enabled before launching the map activity in my app. I'm getting a null pointer exception when calling CheckGPSStatus() in the code below and cannot resolve it.
(I've been pulling my hair out for the last 2 days trying to solve this; I've read loads of questions similar to this already & still can't solve it. I've also cut and paste a different programs code and while it works in its own project, when i practically copy it into my project it doesn't work in mine).
Any and all help gratefully received!
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at com.example.racewatch.MainActivity.CheckGPSStatus(MainActivity.java:64)
at com.example.racewatch.MainActivity$1.onClick(MainActivity.java:46)
MainActivity.java
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button launch_button;
boolean gps_enabled = false;
boolean internet_enabled = false;
Context context;
LocationManager lm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
launch_button = findViewById(R.id.launch_button);
launch_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick (View view){
CheckGPSStatus();
CheckLocationStatus();
if (gps_enabled && internet_enabled) {
Intent i = new Intent(getApplicationContext(), Route.class);
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "Please enable Date & GPS Location", Toast.LENGTH_SHORT).show();
}
} // end of OnClick
// TODO: need to check for older build versions
}); // end of onClickListener
} // end of onCreate method
public void CheckGPSStatus() {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public void CheckLocationStatus() {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
internet_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
} // end of class```
In this case, the problem is that the context
field has not been initialized. However, you are in an Activity
, which is itself a Context
, so you don't need that field in the first place. Just call getSystemService()
directly:
public void CheckGPSStatus() {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}