I am encountering a null pointer exception whenever i click the “OK” button in my dialog box.
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();
}
}
Here is the error
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)
My layout it this
<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>
It seems like when i enter the text inside the EditText, the value is not being read..
EditText text = (EditText)findViewById(R.id.editTextAdd);
Is this the cause of the null pointer because the line points to (text.getText().toString()? If it is, how can i get the value of the text?
Thank you
Because
EditText textis NULL. You are not referringEditText textfrom Dialog Layout.Just Change your line something like, and let me know what happen..
To get
EditTextreference from Dialog Layout you have to usedialogreference withfindViewById()method.Update:
And now access edit text like,