當執行我的onClick方法來顯示editText中的文本的按鈕時,我的應用程序由於NullPointerException而崩潰,我找不到原因。當我完全刪除對editText的引用時,一切正常。我究竟做錯了什麼?onClick從editText獲取文本時崩潰
public void onClick(View v) {
EditText editText1 = (EditText) v.findViewById (R.id.editText1);
switch (v.getId()) {
//add entry to the List
case R.id.button1:
Toast.makeText(getActivity(), "Clicked on add button" + " CRN: " + editText1.getText().toString(), Toast.LENGTH_LONG).show();
case R.id.button2:
Toast.makeText(getActivity(), "Clicked on delete button", Toast.LENGTH_LONG).show();
}
}
錯誤的問題:
01-12 19:32:57.726: E/AndroidRuntime(23216): FATAL EXCEPTION: main
01-12 19:32:57.726: E/AndroidRuntime(23216): java.lang.NullPointerException
01-12 19:32:57.726: E/AndroidRuntime(23216): at com.example.project.ClassesFragment.onClick(ClassesFragment.java:85)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.view.View.performClick(View.java:4475)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.view.View$PerformClick.run(View.java:18786)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.os.Handler.handleCallback(Handler.java:730)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.os.Handler.dispatchMessage(Handler.java:92)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.os.Looper.loop(Looper.java:137)
01-12 19:32:57.726: E/AndroidRuntime(23216): at android.app.ActivityThread.main(ActivityThread.java:5419)
01-12 19:32:57.726: E/AndroidRuntime(23216): at java.lang.reflect.Method.invokeNative(Native Method)
01-12 19:32:57.726: E/AndroidRuntime(23216): at java.lang.reflect.Method.invoke(Method.java:525)
01-12 19:32:57.726: E/AndroidRuntime(23216): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
01-12 19:32:57.726: E/AndroidRuntime(23216): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
01-12 19:32:57.726: E/AndroidRuntime(23216): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
01-12 19:32:57.726: E/AndroidRuntime(23216): at dalvik.system.NativeStart.main(Native Method)
01-12 19:33:12.040: I/Process(23216): Sending signal. PID: 23216 SIG: 9
你的情況下的值,可能爲空。你有沒有在onClick之前正確實例化它們? – SoulRayder
你能告訴我們你的onClick方法嗎? – Raghunandan
在每種情況下使用break並且空指針是因爲你可能會給出錯誤的ID – jyomin