我有一個類,用戶可以動態生成EditText視圖。我打算驗證他們檢查用戶是否繼續下一頁時是否爲空。如果是,則驗證觸發器會暫停移動到其他頁面的過程,直到用戶填充他/她創建的EditText字段。驗證動態生成的EditTexts
以下是我有:
EditText上一代
int EditTextID = 5000;
insertPoint = findViewById(R.id.questionsContainer);
if(v.getId() == R.id.makeLayoutButton){
//get form template which has an EditText of id "questionAnswerEt"
v1 = vi.inflate(R.layout.form_template, null);
//add it into my view
((LinearLayout) insertPoint).addView(v1);
v1.setId(formParentID);
//get edittext
questionAnswer = (EditText)v1.findViewById(R.id.questionAnswerET);
//set id
questionAnswer.setId(EditTextID);
EditTextID++;
}
驗證
if(v.getId() == R.id.bNext){
for(int x = 5000; x <= 5007; x++){
questionAnswer = (EditText)findViewById(x);
String questionAnswerValidator = (String) questionAnswer.getText().toString();
if(questionAnswerValidator.length() == 0){
((EditText) questionAnswer.findViewById(x))
.setError("Question Title is Required!");
}
}
}
循環在5000開始,因爲生成EditTexts還有啓動手動集ID從5000開始,然後每當用戶決定屬時增加另一個EditText。然後,我通過引用「questionAnswer」來遍歷這些ID來獲取EditText。然後,我將questionAnswer(x的id)的字符串值放入字符串「questionAnswerValidator」中。然後檢查它是否爲空,如果是,它會在適當的EditTexts上產生一個setError消息,這些消息是空的。問題是,當驗證開始給我一個空指針異常時,應用程序崩潰。任何線索我要去哪裏錯了?謝謝。
登錄:
08-27 14:27:02.084: W/dalvikvm(16285): threadid=1: thread exiting with uncaught exception (group=0x4166fe18)
08-27 14:27:02.084: E/AndroidRuntime(16285): FATAL EXCEPTION: main
08-27 14:27:02.084: E/AndroidRuntime(16285): Process: com.example.testing, PID: 16285
08-27 14:27:02.084: E/AndroidRuntime(16285): java.lang.NullPointerException
08-27 14:27:02.084: E/AndroidRuntime(16285): at com.example.testing.MakeQuestion.onClick(MakeQuestion.java:212)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.view.View.performClick(View.java:4480)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.view.View$PerformClick.run(View.java:18686)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.os.Handler.handleCallback(Handler.java:733)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.os.Handler.dispatchMessage(Handler.java:95)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.os.Looper.loop(Looper.java:157)
08-27 14:27:02.084: E/AndroidRuntime(16285): at android.app.ActivityThread.main(ActivityThread.java:5872)
08-27 14:27:02.084: E/AndroidRuntime(16285): at java.lang.reflect.Method.invokeNative(Native Method)
08-27 14:27:02.084: E/AndroidRuntime(16285): at java.lang.reflect.Method.invoke(Method.java:515)
08-27 14:27:02.084: E/AndroidRuntime(16285): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
08-27 14:27:02.084: E/AndroidRuntime(16285): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
08-27 14:27:02.084: E/AndroidRuntime(16285): at dalvik.system.NativeStart.main(Native Method)
@andruboy完成。 – Frisbetarian 2014-08-27 11:29:33
也把按鈕單擊代碼我認爲你沒有註冊按鈕onClickListener(this); – MilapTank 2014-08-27 11:31:57
@andruboy它正在註冊按鈕單擊。我有靜態EditText字段驗證,並在用戶點擊「bNext」時工作正常。當我添加動態EditTexts的驗證時,它開始崩潰。 – Frisbetarian 2014-08-27 11:37:50