问题
Many people have faced similar issues, and I think I have followed and fixed all the issues as mentioned in all those posts on stackoverflow.
- setContentView to my layout
- initializing the edittext with dialog.findViewById
But I am still stuck at the nullpointer. What am I missing ?
Layout name is serverchange.xml. Contents of serverchange.xml are
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/server"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textUri" />
<TextView
android:id="@+id/status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true" />
</LinearLayout>
Dialog is created on by selecting a menu on optionsmenu.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.serverChange:
showDialog(SERVER_CHANGE);
// newGame();
return true;
}
}
I get a NullPointerException at
if (changeServerView == null) throw new NullPointerException() ;
Code:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case SERVER_CHANGE:
serverChangeDialog = new Dialog(this);
serverChangeDialog.setContentView(R.layout.serverchange);
serverChangeDialog.setTitle("Change Server");
serverChangeDialog.setOnKeyListener(this);
serverChangeDialog.show();
changeServerView = (EditText) serverChangeDialog.findViewById(R.id.serverChange);
status = (TextView) serverChangeDialog.findViewById(R.id.status);
if (changeServerView == null) throw new NullPointerException() ;
}
return null;
}
My onKey implementation
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (dialog == serverChangeDialog) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
String backupServer = server;
server = changeServerView.getText().toString();
Here too I get a NullPointerException.
回答1:
Wrong id refrences from xml file,
Use server
instead of serverChange
changeServerView = (EditText) serverChangeDialog.findViewById(R.id.server);
^^^^^^
来源:https://stackoverflow.com/questions/10828901/custom-dialog-edittext-returns-null