我试图在我的Activity中实例化一个Dialog。
public void createOptionsMenu() {
Log.e("ActivityContext null?","" + myActivity.this);
myOptionsDialog = new Dialog(myActivity.this); //throwsNPE
myOptionsDialog.setContentView(R.layout.options_dialog);
myOptionsDialog.show();
}
由于您可以在上面看到Log.e,我知道我的activity-context
不是空的!
12-21 15:17:15.466: E/ActivityContext null?(3774): com.android.myproject.myActivity@41fd9af0
12-21 15:17:15.469: E/AndroidRuntime(3774): java.lang.NullPointerException
我认为问题在于我从另一个只有createOptionsMenu()
来自ApplicationContext
的班级拨打myActivity
。如果是这样,我如何在不将ActivityContext
传递给调用createOptionsMenu
的其他类的情况下创建我的Dialog。
感谢任何帮助。
更新
12-21 15:17:15.469: E/AndroidRuntime(3774): FATAL EXCEPTION: main
12-21 15:17:15.469: E/AndroidRuntime(3774): java.lang.NullPointerException
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:140)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.app.Dialog.<init>(Dialog.java:154)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.app.Dialog.<init>(Dialog.java:131)
12-21 15:17:15.469: E/AndroidRuntime(3774): at com.android.myproject.myActivity.createOptionsMenu(myActivity.java:798)
12-21 15:17:15.469: E/AndroidRuntime(3774): at com.android.myproject.WorkerClass$2.onItemLongClick(WorkerClass.java:448)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.widget.AbsListView.performLongPress(AbsListView.java:2883)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2833)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.os.Handler.handleCallback(Handler.java:725)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.os.Handler.dispatchMessage(Handler.java:92)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.os.Looper.loop(Looper.java:153)
12-21 15:17:15.469: E/AndroidRuntime(3774): at android.app.ActivityThread.main(ActivityThread.java:5338)
12-21 15:17:15.469: E/AndroidRuntime(3774): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 15:17:15.469: E/AndroidRuntime(3774): at java.lang.reflect.Method.invoke(Method.java:511)
12-21 15:17:15.469: E/AndroidRuntime(3774): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-21 15:17:15.469: E/AndroidRuntime(3774): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-21 15:17:15.469: E/AndroidRuntime(3774): at dalvik.system.NativeStart.main(Native Method)
实例化活动:
myActivity myActivity_ = new myActivity();
WeakReference<myActivity> myWeakActivity = new WeakReference<myActivity>(myActivity_);
myWeakActivity.get().createOptionsMenu();
答案 0 :(得分:0)
问题在于背景。当我创建一个新的活动对象时,旧的活动不是有效的&#34;内部&#34;新的对象。
解决方法是简单地将Activity-Context
传递给createOptionsMenu
,然后执行此操作:
MyActivity myActivity_ = (MyActivity) context;
然后你可以参考你真正想要的资源。
希望它对某人有帮助。