首页 > 解决方案 > android getContentResolver() 订单问题

问题描述

项目结构 我试图在 MyLocationListenerActivity 中获取 ContentResolver 以访问此处作为 LogContentProvider 实现的数据库。我已将 MyLocationListenerActivity 注册到 MainActivity 中的 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) {
    }

标签: android

解决方案


推荐阅读