So while I was making my first project in android studio, I tried making an alert box where I can take inputs from 2 EditTexts and take them as arguments for creating an RecyclerView Element, but it turns out it's returning null (even though IDs of the EditTexts are mentioned correctly)
fa = findViewById(R.id.add_alarm_fab);
fa.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
builder.setTitle("Add slots");
View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog_layout,null);
builder.setView(customLayout);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
EditText editText1 = findViewById(R.id.edCentre);
EditText editText2 = findViewById(R.id.edSlots);
String centreName = editText1.getText().toString();
Integer slots = Integer.parseInt(editText2.getText().toString());
if (centreName!=null && slots!=null)
medCentreArrayList.add(new MedCentre(centreName,slots));
ad.notifyDataSetChanged();
}
});
builder.create().show();
}
});
This is my XML file for the alert dialog:-
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edSlots"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:ems="10"
android:hint="Slots available"
android:inputType="textPersonName"
android:padding="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="@+id/edCentre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:padding="20dp"
android:ems="10"
android:hint="Centre Name"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="@+id/edSlots"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Looks like you need to find your view in the dialog container, something like this:
EditText editText1 = customLayout.findViewById(R.id.edCentre);