我想在android中将纯色设置为墙纸,但是当我单击按钮时,该应用程序不幸停止了。
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WallpaperManager wm = WallpaperManager.getInstance(getApplicationContext());
try {
wm.setResource(R.color.red);
Toast.makeText(getApplicationContext(), "Wallpaper changed", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
这是colors.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff4366</color>
</resources>
日志猫:
10-24 15:59:26.216 12529-12529/com.danish.testapp D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
10-24 15:59:26.216 12529-12529/com.danish.testapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.danish.testapp, PID: 12529
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
at android.content.res.Resources.openRawResource(Resources.java:1271)
at android.content.res.Resources.openRawResource(Resources.java:1241)
at android.app.WallpaperManager.setResource(WallpaperManager.java:739)
at com.danish.testapp.MainActivity$1.onClick(MainActivity.java:30)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我还在清单中设置了所需的权限。