我在使用 AsyncTask 填充 ListView 时遇到问题。通常它工作正常,但速度非常慢。所以我实现了 AsyncTask,它应该返回值,然后适配器可以使用它们在 ListView 中显示。
但是,如果我运行它,它会在值上返回 nullPointerException。
值和数据源都是全局变量,因此它应该在那里造成任何伤害。当线程不被使用时,它们都可以工作。
这可能是因为它是异步的线程没有创建值,因此它转到 nullPointer,那么我应该什么时候加载这些值?
MyAsynch myAs = new MyAsynch();
myAs.execute();
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
private class MyAsynch extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void...strings) { // run time intensive task in separate thread
datasource = new ReadingsDataSource(getApplicationContext());
datasource.open();
values = datasource.getAllReadings();
datasource.close();
return null;
}
};
这是错误:
08-20 12:21:32.107: E/AndroidRuntime(6896): FATAL EXCEPTION: main
08-20 12:21:32.107: E/AndroidRuntime(6896): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3952)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.ActivityThread.access$1300(ActivityThread.java:128)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.os.Handler.dispatchMessage(Handler.java:99)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.os.Looper.loop(Looper.java:137)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.ActivityThread.main(ActivityThread.java:4514)
08-20 12:21:32.107: E/AndroidRuntime(6896): at java.lang.reflect.Method.invokeNative(Native Method)
08-20 12:21:32.107: E/AndroidRuntime(6896): at java.lang.reflect.Method.invoke(Method.java:511)
08-20 12:21:32.107: E/AndroidRuntime(6896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
08-20 12:21:32.107: E/AndroidRuntime(6896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
08-20 12:21:32.107: E/AndroidRuntime(6896): at dalvik.system.NativeStart.main(Native Method)
08-20 12:21:32.107: E/AndroidRuntime(6896): Caused by: java.lang.NullPointerException
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
08-20 12:21:32.107: E/AndroidRuntime(6896): at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
08-20 12:21:32.107: E/AndroidRuntime(6896): ... 11 more