В файле activity_main.xml есть кнопка, открывающая AlertDialog с двумя полями текстового сообщения (dialog_login.xml); но когда я нажимаю кнопку «Войти», я пытаюсь сохранить содержимое текстового сообщения в строке и получаю следующий результат: «попытка вызвать виртуальный метод для ссылки на нулевой объект». Я заметил, что если я помещаю EditText в файл activity_main.xml с тем же идентификатором, что и в диалоговом окне предупреждения, я не получаю ошибки, поэтому программа ищет EditText в activity_main.xml, а не в dialog_login. xml. Как я могу сделать? Спасибо
Вот мой код:
MainActivity.java
public class MainActivity extends AppCompatActivity {
LayoutInflater inflater;
EditText mUsername;
EditText mPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button);
inflater = MainActivity.this.getLayoutInflater();
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
mBuilder.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
try
{ String username = mUsername.getText().toString(); }
catch(Exception e)
{ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }
}
});
mBuilder.show();
}
});
}
}
activity_main.xml
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.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:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = "com.example.rese.login_session_dialog.MainActivity">
<Button
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Button" />
</android.support.constraint.ConstraintLayout>
dialog_login.xml
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:orientation = "vertical" android:layout_width = "match_parent"
android:layout_height = "match_parent">
<TextView
android:id = "@+id/logintext"
android:layout_gravity = "center"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textSize = "25dp"
android:text = "Login Phase" />
<EditText
android:id = "@+id/username"
android:layout_gravity = "center"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:ems = "10"
android:inputType = "textPersonName"
android:hint = "Username" />
<EditText
android:id = "@+id/password"
android:layout_gravity = "center"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:ems = "10"
android:inputType = "textPassword"
android:hint = "Password" />
</LinearLayout>
Ваш EditText не находится внутри вашей схемы действий, вы не можете выполнить findViewById напрямую
У findViewById это нравится
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
Вместо этого
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
FYI Вы можете использовать вот так
mUsername = v.findViewById(R.id.username);
mPassword = v.findViewById(R.id.password);
Вы пропустили ссылка на диалог до получения диалоговых окон
ваша ссылка на диалог - "v".
сделайте так, чтобы ваши диалоговые окна выглядели так
mUserName = (EditText) dialogRefernce.findviewById (R.id.username);
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
Ссылка на ваш диалог сохранена в 'v'. Без использования диалогового окна (просмотра) вы не можете получать просмотры.
Я думаю, твоя проблема здесь
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
и конкретно здесь
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
Это означает, что вы хотите найти свой текст в макете действия
FindViewById должен быть из макета, где есть виджеты
так это будет правильно
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
Это из-за того, что вы не видите вид из надутого макета.
Вам просто нужно заменить это
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
этим
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
v - это фактическое представление, которое содержит ваш Редактировать текст.
по умолчанию findViewById получает представление из привязанного макета Activity, который из activity_main, и у него нет EdiText вашего диалога, поэтому он дает NullPointerException.
The way you find ID is incorrect Please replace
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
mBuilder.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
try
{ String username = mUsername.getText().toString(); }
catch(Exception e)
{ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }
}
});
mBuilder.show();
}
});
}
@ Лоренцо рад помочь тебе