When I fetch data from firebase real time database and try to store it in string variable, the application gets crashed. I want to display data in AlertDialog box. I've attached logcat image along with structure of database.
Declared variables:
String dayselected,name,slotdata;
Spinner code:
days.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dayselected = daysArray[position];
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Data search button code:
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
backbtn.setVisibility(View.GONE);
logout.setEnabled(false);
search.setEnabled(false);
days.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
if(!TextUtils.isEmpty(facultyname.getText().toString())){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child(name).child(dayselected);
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
slotdata = snapshot.child("Slot1").getValue().toString() + "\n" +
snapshot.child("Slot2").getValue().toString() + "\n" +
snapshot.child("Slot3").getValue().toString() + "\n" +
snapshot.child("Slot4").getValue().toString() + "\n" +
snapshot.child("Slot5").getValue().toString() + "\n" +
snapshot.child("Slot6").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
AlertDialog.Builder dialog = new AlertDialog.Builder(StudentLoggedIn.this);
dialog.setTitle("Time Slots");
dialog.setMessage(slotdata);
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
else {
backbtn.setVisibility(View.VISIBLE);
logout.setEnabled(true);
search.setEnabled(true);
days.setEnabled(true);
progressBar.setVisibility(View.GONE);
Toast.makeText(StudentLoggedIn.this, "Empty Faculty Name Field", Toast.LENGTH_SHORT).show();
}
}
});
Firebase Database:
Logcat: