我正在创建一个AlertDialog,我可以在SQLite数据库中输入一个新值。如果我在onCreate()方法中单独调用Insert方法,则该方法有效,但是当我尝试在setPositiveButton onClick侦听器中调用该方法时,它不起作用,它会给我一个java.lang.NullPointerException错误。我试图将值保存到变量并将其传递给方法,它仍然给我相同的错误,我尝试分配值。有谁知道我做错了什么,谢谢。
public void onAddItemClick(View view){
// get the add_item view
LayoutInflater layoutInflater = LayoutInflater.from(context);
View addView = layoutInflater.inflate(R.layout.add_item, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// Set add_item to alertdialog builder
alertDialogBuilder.setView(addView);
final EditText insertValue = (EditText)findViewById(R.id.txtInsert);
// Set Dialog Message
alertDialogBuilder.setCancelable(false).setPositiveButton("Add to Database",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
// Will Create a new course and insert into the database
insertNewCourse(insertValue.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int id) {
dialogInterface.cancel();
}
});
// Create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it now
alertDialog.show();
}
这是logcat消息
java.lang.NullPointerException
at com.example.gradetracker.app.MainActivity$2.onClick(MainActivity.java:77)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
转换为.toString()
之前检查null
if(insertValue.getText() != null) {
insertNewCourse(insertValue.getText().toString());
}