我已设置GridView
来保存从SD卡加载的一些图像。但是,有很多图像需要加载,因此我决定使用AsyncTask
在后台线程上运行加载和重新采样任务,并在加载完图像后将图像添加到GridView
。不幸的是,每当我运行代码时,我都会遇到这个错误:
01-01 19:49:40.239: E/AndroidRuntime(3851): FATAL EXCEPTION: main
01-01 19:49:40.239: E/AndroidRuntime(3851): java.lang.NullPointerException
01-01 19:49:40.239: E/AndroidRuntime(3851): at com.stullich.tim.woistmeinphoto.PhotoGalleryActivity.addImage(PhotoGalleryActivity.java:199)
01-01 19:49:40.239: E/AndroidRuntime(3851): at <packagename>.PhotoGalleryActivity.access$0(PhotoGalleryActivity.java:195)
01-01 19:49:40.239: E/AndroidRuntime(3851): at <packagename>.PhotoGalleryActivity$FileFetcher.onProgressUpdate(PhotoGalleryActivity.java:226)
01-01 19:49:40.239: E/AndroidRuntime(3851): at <packagename>.PhotoGalleryActivity$FileFetcher.onProgressUpdate(PhotoGalleryActivity.java:1)
01-01 19:49:40.239: E/AndroidRuntime(3851): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:618)
01-01 19:49:40.239: E/AndroidRuntime(3851): at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 19:49:40.239: E/AndroidRuntime(3851): at android.os.Looper.loop(Looper.java:137)
01-01 19:49:40.239: E/AndroidRuntime(3851): at android.app.ActivityThread.main(ActivityThread.java:4514)
01-01 19:49:40.239: E/AndroidRuntime(3851): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 19:49:40.239: E/AndroidRuntime(3851): at java.lang.reflect.Method.invoke(Method.java:511)
01-01 19:49:40.239: E/AndroidRuntime(3851): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
01-01 19:49:40.239: E/AndroidRuntime(3851): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
01-01 19:49:40.239: E/AndroidRuntime(3851): at dalvik.system.NativeStart.main(Native Method)
这是似乎造成麻烦的代码:
final class FileFetcher extends AsyncTask<Void, LoadedImage, Void>
{
private Context mContext;
public FileFetcher(Context context)
{
mContext = context;
}
@Override
protected void onPreExecute()
{
loadImages(new File("/mnt/extSdCard/Bilder"));
}
@Override
public void onProgressUpdate(LoadedImage... value)
{
addImage(value);
}
@Override
protected Void doInBackground(Void... rootDir)
{
int i = 1;
for (File f : directories)
{
File[] anImage = f.listFiles();
if (anImage.length > 0)
{
Bitmap aMap = decodeSampledBitmapFromFile(anImage[0], 120, 120);
publishProgress(new LoadedImage(aMap));
i++;
}
}
return null;
}
}
//My addImage method
private void addImage(LoadedImage... value)
{
for (LoadedImage image : value)
{
adapter.addPhoto(image);
adapter.notifyDataSetChanged();
}
}
每次调用addImage
方法时都会发生崩溃。总是返回一个位图,所以我不知道可以抛出NullPointerException
的位置。任何帮助都会非常感激,因为我已经在这个问题上待了很长一段时间。
答案 0 :(得分:4)
我忘了在onCreate
中初始化我的适配器,导致应用程序崩溃。