tap 我试图在MyLocationListenerActivity中获取ContentResolver,以访问在此处实现为LogContentProvider的数据库。我已经在MainActivity中将MyLocationListenerActivity注册到locationManager。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void trackingServiceButtonOnClick(View v) {
startActivity(new Intent(MainActivity.this,
MyLocationListenerActivity.class));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
MyLocationListenerActivity myLocationListener = new MyLocationListenerActivity();
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, myLocationListener);
} catch (SecurityException e) {
Log.d("debug", e.toString());
}
if (getContentResolver() != null) {
Log.d("debug", "I can get content resolver");
}
}
并且在MyLocationListenerActivity中,如果我想在onCreate()中获取getContentResolver(),那很好,但是,如果我尝试在onLocationChanged中获取getContentResolver,则会出现错误“在空对象引用上获取contentResolver()”,有人知道为什么吗这会发生吗?
public class MyLocationListenerActivity extends AppCompatActivity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_location_listener);
// test() works fine here
test();
}
public void test() {
getContentResolver();
}
@Override
public void onLocationChanged(Location location) {
// error will happen here
test();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}