我正在尝试从editText获取文本并将其输入到我的数据库中。我遇到的问题是NullPointerException
一次我尝试提交文本。任何帮助,将不胜感激。
错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
这是来自我的MainActivity:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_add_task:
final EditText text = (EditText)findViewById(R.id.editText);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("what do you want to do next")
.setView(R.layout.custom_view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task;
task = text.getText().toString();
dbHelper.insertNewTask(task);
if(getFragmentRefreshListener()!=null) {
getFragmentRefreshListener().onRefresh();
}
loadTaskList();
}
})
.setNegativeButton("Cancel",null)
.create();
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
我的custom_view.xml:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a task"
android:id="@+id/editText" />
我的activity_main.xml:
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tablayout"
android:background="@color/colorPrimaryDark"
android:minHeight="?attr/actionBarSize"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:backgroundTint="@android:color/darker_gray"
android:visibility="visible">
<ListView
android:id="@+id/lstTask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="@string/tasks"
android:textSize="30sp" />
</android.support.v4.view.ViewPager>
好吧,因为我看不到MainActivity
布局的 xml ,所以这很可能是导致 NPE 的原因。
final EditText text = (EditText)findViewById(R.id.editText);
当(假设从对话框创建中显示的内容)您应该在对话框视图层次结构中搜索它时,您在活动视图层次结构中搜索您的编辑文本。
.setView(R.layout.custom_view)
您正在将该视图设置为对话框的视图,这可能是导致异常的原因。尝试像这样在 onClick 方法中细化对编辑文本的引用:
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("what do you want to do next")
.setView(R.layout.custom_view)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final EditText text = ((AlertDialog)dialog).findViewById(R.id.editText);
String task;
task = text.getText().toString();
dbHelper.insertNewTask(task);
if(getFragmentRefreshListener()!=null) {
getFragmentRefreshListener().onRefresh();
}
loadTaskList();
}
})
.setNegativeButton("Cancel",null)
.create();
dialog.show();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句