Android cannot get EditText getText().toString() in dialog… here is a solution to the problem.
Android cannot get EditText getText().toString() in dialog
I’m trying to create a custom dialog in a single class. The dialog box is launched in the main activity:
DialogLogin login = new DialogLogin();
login.show(getFragmentManager(), DISPLAY_SERVICE);
When you start the application, the main activity starts in the background, and then the dialog box starts.
In the dialog box, there is an EditText field to receive user input. When the save button is pressed, the EditText field should be read out and the input displayed, but it is always empty. Also, there are no errors in LogCat… I tried many solutions to the same issue but nothing worked. I hope anyone has a workable solution! =)
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
public class DialogLogin extends DialogFragment {
String androidID;
LayoutInflater inflater;
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
inflater = getActivity().getLayoutInflater();
builder.setMessage(R.string.loginMessage)
.setTitle(R.string.login)
.setView(inflater.inflate(R.layout.loginlayout, null))
.setPositiveButton(R.string.speichern,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.out.println("LOGIN");
View v = inflater.inflate(R.layout.loginlayout, null);
EditText text = (EditText) v.findViewById(R.id.loginEdit);
System.out.println(text.getText().toString()); Displays nothing
System.out.println(text.length()); is 0
}
});
return builder.create();
}
and loginlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/loginEdit"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/editText" >
</EditText>
</LinearLayout>
Solution
You are inflate a new layout with no text in EditText
. You only need to augment your layout once and keep a reference to it.
final View view = inflater.inflate(R.layout.loginlayout, null);
/* ... */
.setView(view)
/* ... */
EditText text = (EditText) view.findViewById(R.id.loginEdit);