I am trying to create a simple dialog box to allow my user to create a new user. I have the layout the way i need it but for some reason when i click the Create button it throws an exception. I have tried various way to accomplish this but i must be leaving something out. I am now on day two of this error and I am all out of options. I have ever re-wrote the code twice and went over with a fine tooth comb.
here is what i have so far:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final HttpClient httpclient = new DefaultHttpClient();
//new user button, work in progress
Button newuser = (Button) findViewById(R.id.new_user);
newuser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog createU = new Dialog(MainActivity.this);
createU.setContentView(R.layout.newuser);
createU.setTitle("Create User");
Button create = (Button) createU.findViewById(R.id.createUsr);
Button cancel = (Button) createU.findViewById(R.id.cancel);
create.setOnClickListener(new View.OnClickListener() {//creates the user
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String usr = null, pass = null;
EditText userU = (EditText) findViewById(R.id.createUsr);
EditText passU = (EditText) findViewById(R.id.cancel);
if(userU.getText()!= null){//throws ERROR/AndroidRuntime(9937): java.lang.NullPointerException
usr = userU.getText().toString();
}
if(passU.getText()!=null){
pass = passU.getText().toString();
}
Toast toast = Toast.makeText(getApplicationContext(), "User: " + usr + ", Pass: " + pass, Toast.LENGTH_SHORT);
toast.show();
}
});
cancel.setOnClickListener(new View.OnClickListener() {//closes dialog
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
createU.hide();
}
});
createU.show();
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<EditText android:id="@+id/usrTxt" android:layout_height="wrap_content"
android:layout_width="match_parent" android:maxLines="1" android:hint="Username"
android:text="2"></EditText>
<EditText android:id="@+id/pasTxt" android:layout_height="wrap_content"
android:layout_width="match_parent" android:layout_below="@id/usrTxt"
android:inputType="textPassword" android:maxLines="1" android:hint="Password"
android:text="2"></EditText>
<Button android:layout_height="wrap_content"
android:layout_alignParentLeft="true" android:layout_width="wrap_content"
android:layout_below="@+id/pasTxt" android:text="Create" android:id="@+id/createUsr"></Button>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/cancel"
android:layout_alignParentRight="true" android:text="Cencel"
android:layout_below="@+id/pasTxt"></Button>
Do not initialize strings with null values
avoid
String usr = null, pass = null;. Hope that will help.Update:
Change the above line causing error as
Update2
Change the Edittext initialization lines as below