我有两个班,MainActivity
和DoHardWork
。DoHardWork extends AsyncTask
,并且在类中我需要访问上下文才能获取contentResolver
并执行查询。
没问题,对吧?让我们将它作为参数传递给DoHardWork
:
Context currCont = this;
new DoHardWork(currCont).execute();
然后在构造函数中,我获取上下文并将其存储在一个名为ccc
.
但是,一旦我尝试访问上下文,它就会崩溃,没有任何有意义的错误。
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();
}
我得到的是:
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)
为什么我无法访问上下文?