每当我单击对话框中的“确定”按钮时,都会遇到空指针异常。
public class TestActivity extends ListActivity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_bucket_crud);
}
public void addTestItem(View view) {
LayoutInflater inflater = getLayoutInflater();
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setIcon(R.drawable.add)
.setView(inflater.inflate(R.layout.activity_bucket_crudadd, null))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText text = (EditText)findViewById(R.id.editTextAdd);
DatabaseHandler myDbHelper = new DatabaseHandler(context);
myDbHelper.insertItem(text.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}).show();
}
}
这是错误
01-05 09:20:35.052: E/AndroidRuntime(761): FATAL EXCEPTION: main
01-05 09:20:35.052: E/AndroidRuntime(761): java.lang.NullPointerException
01-05 09:20:35.052: E/AndroidRuntime(761): at com.example.test.TestActivity$1.onClick(TestActivity.java:65)
01-05 09:20:35.052: E/AndroidRuntime(761): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
我的布局是这样
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="150dp">
<EditText
android:id="@+id/editTextAdd"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="textMultiLine"
android:layout_margin="5dp"
android:padding="3dp">
<requestFocus />
</EditText>
</RelativeLayout>
似乎当我在 EditText 中输入文本时,没有读取该值..
EditText text = (EditText)findViewById(R.id.editTextAdd);
这是因为该行指向空指针(text.getText().toString()
的原因吗?如果是,我怎样才能得到文本的价值?
谢谢