Can't access getContentResolver() from context

2019-09-20 19:15发布

问题:

I have two classes, MainActivity and DoHardWork. DoHardWork extends AsyncTask, and in the class I need to access a context in order to get the contentResolver and do a query.

No problem, right? Let's just pass it as a parameter to DoHardWork:

    Context currCont = this;
    new DoHardWork(currCont).execute();

Then in the constructor I grab the context and store it in a global variable called ccc.

But as soon as I try to access the context it crashes, with no errors that make sense.

try {
    Cursor cursor = ccc.getContentResolver().query(
            Uri.parse("content://sms/inbox"), null, null, null, null);
}
catch (Exception e) {
    Log.e("apptag", e.getMessage());
    e.printStackTrace();
}

All I get is:

05-18 18:54:06.725: E/apptag(29063): Crashed
05-18 18:54:06.725: E/apptag(29063): java.lang.NullPointerException
05-18 18:54:06.725: E/apptag(29063):    at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
05-18 18:54:06.725: E/apptag(29063):    at se.jbhalmstad.ndroid.DoHardWork.getTextMessages(DoHardWork.java:214)
05-18 18:54:06.725: E/apptag(29063):    at se.jbhalmstad.ndroid.DoHardWork.returnResults(DoHardWork.java:114)
05-18 18:54:06.725: E/apptag(29063):    at se.jbhalmstad.ndroid.DoHardWork.doInBackground(DoHardWork.java:55)
05-18 18:54:06.725: E/apptag(29063):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
05-18 18:54:06.725: E/apptag(29063):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-18 18:54:06.725: E/apptag(29063):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-18 18:54:06.725: E/apptag(29063):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-18 18:54:06.725: E/apptag(29063):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-18 18:54:06.725: E/apptag(29063):    at java.lang.Thread.run(Thread.java:856)

Why can't I access the context?

回答1:

Found the problem.

The way it works is that from the MainActivity class, i set a repeating AlarmManager. When the alarm goes off the GetOperations class acts as a BroadcastReceiver and gets executed. Because i need the heavy work in an AsyncTask class i have all of that in a class called DoHardWork. (Yes, i know the names are bad and most of the coding needs improvement anyways) But i can't call DoHardWork from the BroadcastReceiver, i need to call it from MainActivity. So instead of trying to call it from BroadcastReceiver i then create a new instance of MainActivity and call a method in there which then calls DoHardWork. That's where i made the problem. MainActivity isn't static, so when i made a new instance of it there was no context.

What i ended up doing is passing a context from BroadcastReceiver to MainActivity.

This probably got very messy while explaining, but i hope you get the gist of it. Thank you for all the help!