这个问题问了很多遍,但是没有答案可以解决我的问题。我是新的android开发人员,所以请给我答复我的问题。我的问题是,当我启动LocSettingsActivity以查找位置并尝试将putStringValue设置为CITY时,发生了异常 Logcat错误是:
09-09 14:54:46.353 10099-10099/com.psadi.psad.TSGS E/PSAD: Exception occurd -> Attempt to invoke virtual method 'void com.psadi.psad.TSGS.preferences.AppPreferences.putStringValue(java.lang.String, java.lang.String)' on a null object reference
09-09 14:54:46.353 10099-10099/com.psadi.psad.TSGS W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.psadi.psad.TSGS.preferences.AppPreferences.putStringValue(java.lang.String, java.lang.String)' on a null object reference
09-09 14:54:46.354 10099-10099/com.psadi.psad.TSGS W/System.err: at com.psadi.psad.TSGS.LocSettingsActivity.getAddress(LocSettingsActivity.java:289)
at com.psadi.psad.TSGS.LocSettingsActivity.callLocationGpsTracker(LocSettingsActivity.java:252)
at com.psadi.psad.TSGS.LocSettingsActivity.locationEnabled_or_Not(LocSettingsActivity.java:213)
at com.psadi.psad.TSGS.LocSettingsActivity.checkPermission(LocSettingsActivity.java:172)
at com.psadi.psad.TSGS.LocSettingsActivity.onCreate(LocSettingsActivity.java:53)
at android.app.Activity.performCreate(Activity.java:6860)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2674)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2782)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1521)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6228)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
我的项目代码是:
public class LocSettingsActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback {
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest locationRequest;
int REQUEST_CHECK_SETTINGS = 100;
private AppPreferences mPrefs;
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Step 1
checkPermission();
mPrefs = AppPreferences.getAppPreferences(LocSettingsActivity.this);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult result =
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
builder.build()
);
result.setResultCallback(this);
mPrefs = AppPreferences.getAppPreferences(LocSettingsActivity.this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onResult(@NonNull Result locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// NO need to show the dialog;
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. Show the user a dialog
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(LocSettingsActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
//failed to show
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are unavailable so not possible to show any dialog now
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "GPS enabled", Toast.LENGTH_LONG).show();
Log.e("PSAD", "..........GPS enabled..............");
//TODO Important When Gps Enable Just Now Need Some Time ..........otherwise lat long 0.0 fetch
// TODO Need Some time to call GPS Tracker Service
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000); //Todo dummy delay for 2 second
} catch (InterruptedException e) {
e.printStackTrace();
}
//update ui on UI thread
runOnUiThread(new Runnable() {
@Override
public void run() {
callLocationGpsTracker();
}
});
}
}).start();
} else {
callLocationDialog();
Log.e("PSAD", "..........GPS not enabled..............");
Toast.makeText(getApplicationContext(), "GPS is not enabled", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void checkPermission(){
if (!hasGPSDevice(LocSettingsActivity.this)) {
Log.e("PSAD", "Gps not Supported");
Toast.makeText(LocSettingsActivity.this, "Gps not Supported", Toast.LENGTH_SHORT).show();
} else {
Log.e("PSAD", "Gps Supported ---hasGPSDevice return true--Step 1 Pass...........");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(LocSettingsActivity.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Log.e("permission", "granted");
locationEnabled_or_Not();
} else {
ActivityCompat.requestPermissions(LocSettingsActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,}, 1);
}
} else {
Log.e("MainActivity", "Lower Than MarshMallow");
locationEnabled_or_Not();
}
}
}
//TODO Step 1
public boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null)
return false;
final List<String> providers = mgr.getAllProviders();
if (providers == null)
return false;
return providers.contains(LocationManager.GPS_PROVIDER);
}
//TODO Step 2
// TODO When Location not enabled show popup
// TODO When Location already Enabled CAll GPS Tracker
private void locationEnabled_or_Not() {
Log.e("PSAD", "locationEnabled_or_Not Step 2 Pass...........");
final LocationManager manager = (LocationManager) LocSettingsActivity.this.getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocSettingsActivity.this)) {
Log.e("PSAD", "Gps not enabled");
callLocationDialog();
} else {
Log.e("PSAD", "Gps already enabled");
callLocationGpsTracker(); // TODO When Gps already enabled call direct GPS Tracker
}
}
//TODO Step 3 when hasGPSDevice return true
private void callLocationDialog() {
Log.e("PSAD", "callLocationDialog Step 3 Popup called ...........");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
}
//TODO Step 4 when location on fetch GPS Tracker Through Latitude Longitude
private void callLocationGpsTracker() {
Log.e("PSAD", "callLocationGpsTracker Step 4 Called ... fetch Location");
gps = new GPSTracker(LocSettingsActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Log.e("MainActivity", "latitude -> " + latitude);
Log.e("MainActivity", "longitude -> " + longitude);
getAddress(latitude, longitude);
} else {
// TODO can't get location
// TODO GPS or Network is not enabled
// TODO Ask user to enable GPS/network in settings
//TODO need again call Locaton Dialog
callLocationDialog();
}
}
private void getAddress(double lat, double lon) {
String cityName = "";
String stateName = "";
String postalCode = "";
String countryName = "";
StringBuilder finalAddress = new StringBuilder();
try {
Geocoder geocoder = new Geocoder(LocSettingsActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null) {
try {
cityName = addresses.get(0).getLocality();
stateName = addresses.get(0).getAdminArea();
countryName = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
if (cityName != null)
mPrefs.putStringValue(AppPreferences.CITY, cityName);
if (addresses.get(0).getAddressLine(0) != null)
finalAddress.append(addresses.get(0).getAddressLine(0));
if (addresses.get(0).getAddressLine(1) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(1));
if (addresses.get(0).getAddressLine(2) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(2));
if (addresses.get(0).getAddressLine(3) != null)
finalAddress.append(" " + addresses.get(0).getAddressLine(3));
Log.e("PSAD", "addres 0 -> " + addresses.get(0).getAddressLine(0));
Log.e("PSAD", "addres 1 -> " + addresses.get(0).getAddressLine(1));
Log.e("PSAD", "addres 2 -> " + addresses.get(0).getAddressLine(2));
Log.e("PSAD", "addres 3 -> " + addresses.get(0).getAddressLine(3));
Log.e("PSAD", "addres final -> " + finalAddress);
} catch (Exception e) {
Log.e("PSAD", "Exception occurd -> " + e.getMessage());
e.printStackTrace();
}
Log.e("PSAD", "cityName -> " + cityName);
Log.e("PSAD", "stateName -> " + stateName);
Log.e("PSAD", "countryName -> " + countryName);
Log.e("PSAD", "PostalCode -> " + postalCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
似乎引起问题的错误行是:
mPrefs.putStringValue(AppPreferences.CITY, cityName);