2

I am struggling to learn how XML layouts in android work. I suspect my question has been asked before, but I can't find the answer. I am looking at the APIDemos tutorial that comes with the android SDK. There is a class called AlertDialogSamples in it. I am working with the custom DIAGLOG_TEXT_ENTRY case. I understand how to get the view to be added to the dialog box and how to make the labels and text box change. I cannot understand how to get the user input text from the boxes and do somethign with it. In the lines:

.setPositiveButton(R.string.alert_dialog_ok,
   new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
         /* User clicked OK so do some stuff */
     }

How do I get the user input values of the username and password fields and use them where is says User clicked OK? They should be EditText objects, but I am unfamiliar with how to access these fields since they are formed using XML instead of writting them in JAVA. How do I access XML generated objects?

Thank you

2 Answers 2

1

You need to set ids on the EditText fields in your layout xml:

<EditText android:id="@+id/username"
    ... />
<EditText android:id="@+id/password"
    ... />

Then at any time inside your activity you can reference them by:

EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);

You can get their text by using username.getText(), which returns a CharSequence and can be used like a String.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick response! I just tried this, but I get a null pointer exception when I try this. The exception occurs on the getText() line. The getText returns an Editable object. My code is as below: .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { EditText text = (EditText) findViewById(R.id.password_edit); System.out.println(text.getText().toString()); /* User clicked OK so do some stuff */ }
Your view isn't being found. Are you sure that you are loading the right layout?
0

try this..

String string=editText.getText().toString();

if(!string.equals("")){

Toast.makeText(getApplicationContext(),string,Toast.LENGTH_SHORT).show(); System.out.println(string);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.