在我的代码中,我正在从我检查过的文件夹中恢复图像,其中包含图像并且不为空。出于某种原因,当它获得壁纸管理器的setBitmap代码时,似乎停止工作并输出下面的错误。任何帮助,将不胜感激。感谢
Process: coolwallpaper.alexcz.coolwallpaper, PID: 15613
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at android.app.WallpaperManager.setBitmap(WallpaperManager.java:956)
at coolwallpaper.alexcz.coolwallpaper.Main$1.onClick(Main.java:54)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20926)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5951)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
static final File dir = new File("/data/data/coolwallpaper.alexcz.coolwallpaper/app_imageDir/");
Button createWallpaper;
Button setWallpaper;
Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createWallpaper = (Button)findViewById(R.id.createWallpaper);
setWallpaper = (Button)findViewById(R.id.set_wallpaper);
setWallpaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AsyncTask.execute(new Runnable() {
@Override
public void run() {
if (dir.isDirectory()) { // make sure it's a directory
for (File f : dir.listFiles()) {
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
System.out.println(bitmap.getWidth());
}
}
}
});
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
});
createWallpaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Main.this, FractalActivity.class);
startActivity(intent);
}
});
}
答案 0 :(得分:0)
这是因为Async Task在一个单独的线程上运行。更改壁纸的异步任务之前的代码,在后台仍然从文件加载位图时开始执行。这就是为什么setBitmap被称为包含空参数