-1

我正在创建一个涉及创建待办事项列表的 android 应用程序,当调用 onstart 方法时,我可以context.findviewbyid()成功调用一行,但后来它不起作用,这只发生在应用程序以某种方式旋转或重置时

onStart 方法

@Override
public void onStart(){
super.onStart();
this.context = getActivity();
ViewGroup vg = (ViewGroup) context.findViewById(R.id.MainLayout);
databaseHandler = new DatabaseHandler(context, (ViewGroup)
context.findViewById(R.id.MainLayout));
vg.removeAllViews();
databaseHandler.reinstantiateAllWishes();
WishlistCounter = databaseHandler.getWishCount();
databaseHandler.close();
Log.v("onStart WishlistCounter: ", String.valueOf(WishlistCounter));
}

createNew 方法

public void createNew(){
    Log.v("Creating new:","confirmed");
    //Get the message from the Edit Text
    EditText editText = (EditText) context.findViewById(R.id.WishListAddText);
    String message= editText.getText().toString();
    //If it is acceptable, continue
    if(!message.equals("") && WishlistCounter < SLOTS_LIMIT && !message.equals(null)){
        //Create new Wish
        Wish c = new Wish((ViewGroup) context.findViewById(R.id.MainLayout), getActivity(), this.databaseHandler);
        c.newBuilder(message);
        WishlistCounter++;
    //Explain unacceptability
    } else if(WishlistCounter >= SLOTS_LIMIT){
        Toast.makeText(context, "You cannot have over" +  String.valueOf(SLOTS_LIMIT) + "entries" ,Toast.LENGTH_SHORT).show();
    }
}

错误日志

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3039)
at android.view.View.performCLick(View.java:3480)
at android.view.View$PerformClick.run(View,java:13983)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.osLooper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.intenal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(NativeMethod)
Caused by: java.lang.InvocationTargetException
at java.lang.reflect.Method.invokeNative(NativeMethod)
at java.lang.reflect.Method.invoke(Method.java:3034)
... 11 more
Caused by: java.lang.NullPointerException
at com.chesterbane.inspiriappaplpha.Frgmant4.createNew(Fragment4.java:61)
at com.chesterbane.inspiriappalpha.MainActivity.wishlistCreateNew(MainActivity.java:315)
... 14 more

EditText editText = (EditText) context.findViewById(R.id.WishListAddText);是引发异常的行,我认为它是空的上下文。我不明白是什么导致它为空,因为它在 onStart 方法中工作正常。任何帮助将不胜感激

4

1 回答 1

0

在 onStart 方法的第三行,您正在为活动设置上下文。尝试将其设置为上下文。

this.context = getActivity().getApplicationContext();
于 2013-09-01T22:08:11.757 回答