Краш приложения при EditText.getText().ToString()
При попытке считать текст в Alert dialog с внешнего layout происходит краш.
Так выглядит activity для Allert dialog.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rString_add"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".add_rString">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/loggin_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Логин" />
<EditText
android:id="@+id/loggin_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="name" />
<TextView
android:id="@+id/loggin_text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Пароль" />
<EditText
android:id="@+id/loggin_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Не думаю что есть особый смысл вставлять все части кода, поэтому оставим только проблемную часть, поскольку краш происходит на моменте getText();
LayoutInflater inflater = getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.activity_add_rstring, null);
AlertDialog.Builder password_check = new AlertDialog.Builder(MainActivity.this);
AlertDialog pas_check = password_check.create();
pas_check.setTitle("Введите текст");
pas_check.setView(dialoglayout);
pas_check.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String p_login = ((EditText) findViewById(R.id.loggin_password)).getText().toString(); //Проблемное место
String p_pasword = ((EditText) findViewById(R.id.loggin_password)).getText().toString();
if (p_login == "Admin" && p_pasword == "admin")
{
Intent viewStart = new Intent(MainActivity.this, com.example.dyplom.View.class);
startActivity(viewStart);
pas_check.cancel();
}
else {
Toast toast = Toast.makeText(getApplicationContext(), "Неправильный логин или пароль", Toast.LENGTH_SHORT);
toast.show();
((EditText) findViewById(R.id.loggin_password)).setText("");
}
}
});
pas_check.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
pas_check.cancel();
}
});
pas_check.show();
Вывод консоли
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dyplom, PID: 10508
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.dyplom.MainActivity$2$1.onClick(MainActivity.java:63)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Почему может происходить краш?
Ответы (1 шт):
Автор решения: ЮрийСПб
→ Ссылка
Судя по всему приведённый вами код написан в активити и, засим, вызывая метод findViewById в слушателе нажатий кнопки диалога вы вызываете метод активити, который пытается вьюху искать в разметке оной, а не в разметке диалога. Получается в итоге null и закономерный NPE.
Следовательно, надо заменить findViewById на
dialoglayout.findViewById