Removing data from firebase on a RecyclerAdapter - android

I am removing a list item with a PopupMenu on my RecyclerViewAdapter, but when the item is removed it stays on the Firebase.
This is on the onBindViewHolder on the RecyclerAdapter
holder.opcionesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.opcionesButton);
//inflating menu from xml resource
popup.inflate(R.menu.menu_edit);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.edit_item:
//handle menu1 click
break;
case R.id.delete_item:
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
And this is on the MainFragment
final Query tareasQuery = mTareasDatabase.child(userId);
tareasQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Tareas tareas = new Tareas();
tareas.setFecha(dataSnapshot.getValue(Tareas.class).getFecha());
tareas.setDescripcion(dataSnapshot.getValue(Tareas.class).getDescripcion());
tareas.setLista(dataSnapshot.getValue(Tareas.class).getLista());
tareas.setPrioridad(dataSnapshot.getValue(Tareas.class).getPrioridad());
mTareasList.add(tareas);
mTareasAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String tareasId = dataSnapshot.getValue(Tareas.class).getTareasId();
mTareasDatabase.child(userId).child(tareasId).removeValue();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String tareasId = dataSnapshot.getValue(Tareas.class).getTareasId();
mTareasDatabase.child(userId).child(tareasId).removeValue();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Everything is working fine, except that is not deleting it from the firebase
Solution
Remove the item from the firebase and the recycler view at the same time
case R.id.delete_item:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
String tareasId = tareas.getTareasId();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference("Tareas")
.child(userId).child(tareasId);
databaseReference.removeValue();
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;

Okay I solved it. I just had to add all the database references on the delete item, and remove it from the recycler view and the database at the same time
case R.id.delete_item:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
String tareasId = tareas.getTareasId();
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference("Tareas")
.child(userId).child(tareasId);
databaseReference.removeValue();
tareasList.remove(position);
notifyItemRemoved(position);
Toast.makeText(context, "Tareas eliminada!", Toast.LENGTH_SHORT).show();
break;

this is because you are deleting from the local list only. You have to remove the value from firebase too. For deleting use code
firebaseRef.removeValue();
In your firebaseRef you have to show which value you want to delete.

Related

How can we store dropdown selected option string to firestore in android studio

I have String list as shown I want the selected item to be store in Firestore
Can you please tell me how it should be possible?
I have String list as shown I want the selected item to be store in Firestore
Can you please tell me how it should be possible?
public class Student_Register_Activity extends AppCompatActivity {
EditText etRegEmail,etname,etfathername,etRollno,etdepartment,etadress,etphonenmbr,semester,;
EditText etRegPassword;
String[] items={"Shinkiari","Mansehra","Abbottabad","Qalandarabad","Attersheesha","Khaki"};
AutoCompleteTextView autoCompleteText;
Button btnRegister;
ArrayAdapter<String> adapteritems;
FirebaseAuth mAuth;
FirebaseFirestore firestore=FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_register);
autoCompleteText=findViewById(R.id.auto_complete_txt);
adapteritems=new ArrayAdapter<String>(this,R.layout.list_item,items);
autoCompleteText.setAdapter(adapteritems);
autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String item =adapterView.getItemAtPosition(position).toString();
}
});
etRegEmail = findViewById(R.id.etRegEmail);
etRegPassword = findViewById(R.id.etRegPass);
btnRegister = findViewById(R.id.btnRegister);
etname = findViewById(R.id.etname);
etfathername = findViewById(R.id.etfname);
etRollno = findViewById(R.id.etRollno);
etdepartment = findViewById(R.id.etdepartment);
etadress = findViewById(R.id.etadress);
etphonenmbr = findViewById(R.id.etphonenmbr);
mAuth = FirebaseAuth.getInstance();
btnRegister.setOnClickListener(view -> createUser());
}
private void createUser(){
String email = etRegEmail.getText().toString();
String password = etRegPassword.getText().toString();
if (TextUtils.isEmpty(email)){
etRegEmail.setError("Email cannot be empty");
etRegEmail.requestFocus();
}else if (TextUtils.isEmpty(password)){
etRegPassword.setError("Password cannot be empty");
etRegPassword.requestFocus();
}else{
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Student_Register_Activity.this, "Student registered successfully", Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
DocumentReference df = firestore.collection("Student").document(user.getUid());
//Map is used to store the data
Map<String,Object> userinfo = new HashMap<>();
userinfo.put("Name",etname.getText().toString());
userinfo.put("FName",etfathername.getText().toString());
userinfo.put("Email",etRegEmail.getText().toString());
userinfo.put("Password",etRegPassword.getText().toString());
userinfo.put("semester",etRegPassword.getText().toString());
userinfo.put("Transport", adapteritems.toString();
userinfo.put("Rollno",etRollno.getText().toString());
userinfo.put("Department",etdepartment.getText().toString());
userinfo.put("address",etadress.getText().toString());
userinfo.put("phone",etphonenmbr.getText().toString());
startActivity(new Intent(Student_Register_Activity.this, AdminDashboard.class));
//specify if user is student
userinfo.put("isStudent","1");
df.set(userinfo);
}else{
Toast.makeText(Student_Register_Activity.this, "Registration Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I think you want to add selected items from list in user object, If that so you can follow below steps:
first declare global variable for selected
String selectedOption;
Then save value in on click of list
autoCompleteText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
selectedOption =adapterView.getItemAtPosition(position).toString();
}
});
then use that value to save in user object
userinfo.put("city",selectedOption);

How to compare value from radio button with specific value in firebase

I'm trying to assign my radio button value with a specific value in Firebase. But when I run it, I did not get the output. The problem of the coding is here (snapshot.child("Allergy").child("None").getValue().equals(selectedRadioValue2)))) when I'm trying to assign the "None" value. Can anyone help?
dr.addValueEventListener(new ValueEventListener() {
Intent intent = getIntent();
String selectedRadioValue1 = intent.getExtras().getString("SelectedValue1");
String selectedRadioValue2 = intent.getExtras().getString("SelectedValue2");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if ((snapshot.child("Age").getValue().equals(selectedRadioValue1))&&((!snapshot.child("Allergy").getValue().equals(selectedRadioValue2))
|| (snapshot.child("Allergy").child("None").getValue().equals(selectedRadioValue2))))
{
String ingredient = snapshot.child("Ingredient").getValue().toString();
HashSet<String> hashSet = new HashSet<String>();
al.add(ingredient);
hashSet.addAll(al);
al.clear();
al.addAll(hashSet);
Collections.sort(al);
ad.notifyDataSetChanged();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(result.this, "Category Selected", Toast.LENGTH_SHORT).show();
String TempListViewClickedValue = al.get(position).toString();
Intent intent = new Intent (result.this,RecommendedFood.class);
intent.putExtra("1",selectedRadioValue1);
intent.putExtra("2",selectedRadioValue2);
intent.putExtra("RecommendedFood",TempListViewClickedValue);
startActivity(intent);
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is my firebase

How to write Shared preference Code that uses firebase for User authentication?

How do I write Shared-preference Code that is using Firebase for User authentication and the data that is saved by a user is only accessible for them?
My current application Saves a note and displays it which is the main thing needed in my project but when a user logs out and new user logs in he/she can also view the data so the data is not private. My sir suggested to make nodes for users using shared preference but i couldn't find any solutions
HomeActivity:
public class HomeActivity extends AppCompatActivity {
EditText Descriptionholder;
Button Savebtn;
DatabaseReference DatabaseNote;
ListView listViewNotes;
List<PrivateNote> privateNoteList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseNote = FirebaseDatabase.getInstance().getReference("privatenote");
Descriptionholder = findViewById(R.id.description2);
Savebtn = findViewById(R.id.buttonsave);
listViewNotes= findViewById(R.id.listViewPrivate);
privateNoteList = new ArrayList<>();
Savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addnote();
}
});
listViewNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
PrivateNote privateNote = privateNoteList.get(i); //confusion
showUpdateDialog(privateNote.getNoteId(),privateNote.getNoteDescription());
return false;
}
});
}
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.side, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()) {
case R.id.item1:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(new Intent(this, MainActivity.class)));
Toast.makeText(this, "Logged out ", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStart() {
super.onStart();
DatabaseNote.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
privateNoteList.clear();
for (DataSnapshot privateSnapshot: dataSnapshot.getChildren() ){
PrivateNote privateNote = privateSnapshot.getValue(PrivateNote.class);
privateNoteList.add(privateNote);
}
PrivateList adapter = new PrivateList(HomeActivity.this,privateNoteList);
listViewNotes.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUpdateDialog(final String noteId, String noteDescription){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogview = inflater.inflate(R.layout.update_dialouge,null);
dialogBuilder.setView(dialogview);
final EditText editDescription = dialogview.findViewById(R.id.editDescription);
final Button buttonUpdate = dialogview.findViewById(R.id.buttonUpdate);
final Button buttonDelete = dialogview.findViewById(R.id.buttonDelete);
dialogBuilder.setTitle("Updating Note: " +noteDescription);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String description = editDescription.getText().toString().trim();
if (TextUtils.isEmpty(description)){
editDescription.setError(" New information required");
return;
}
updatePrivateNote(noteId,description);
alertDialog.dismiss();
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePrivateNote(noteId);
}
});
}
private void deletePrivateNote(String noteId) {
DatabaseReference drPrivateNote = FirebaseDatabase.getInstance().getReference("privatenote").child(noteId);
drPrivateNote.removeValue();
Toast.makeText(this, " Note Deleted", Toast.LENGTH_SHORT).show();
}
private boolean updatePrivateNote(String id,String description){
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("privatenote").child(id);
PrivateNote privateNote = new PrivateNote(id,description);
databaseReference.setValue(privateNote);
Toast.makeText(this, " Note Updated", Toast.LENGTH_SHORT).show();
return true;
}
private void addnote () {
String description = Descriptionholder.getText().toString().trim();
if (!TextUtils.isEmpty(description)){
//generated unique number for id
String id = DatabaseNote.push().getKey();
PrivateNote pNote = new PrivateNote(id, description);
DatabaseNote.child(id).setValue(pNote); //pNote value added in id
Toast.makeText(this, "Note added", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, " Please Enter a note ", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
FirebaseAuth.getInstance().signOut();
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Adapter:
public class PrivateList extends ArrayAdapter<PrivateNote> {
private Activity context;
private List<PrivateNote> privateNoteList;
public PrivateList(Activity context, List<PrivateNote> privateNoteList){
super(context, R.layout.list_layout,privateNoteList);
this.context =context;
this.privateNoteList=privateNoteList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout,null,true);
TextView textViewDescription = listViewItem.findViewById(R.id.TextViewDescription);
PrivateNote privateNote = privateNoteList.get(position);
textViewDescription.setText(privateNote.getNoteDescription());
return listViewItem;
}
}
PrivateNote:
public class PrivateNote {
public String noteId;
public String noteDescription;
public PrivateNote(){
}
PrivateNote(String noteId, String noteDescription){
this.noteId = noteId;
this.noteDescription=noteDescription;
}
String getNoteId()
{
return noteId;
}
String getNoteDescription()
{
return noteDescription;
}
}
In Firebase, there are two things,
FirebaseDatabase
FirebaseAuth
Usually, in almost all the apps, user data is stored in the FirebaseDatabase under the key, that is generated while creating a new user in your Firebase app.
So, for example, your database structure will look like this.
-Your_main_database
|____UserId_Of_FirebaseUser
|____stuff_related_to_user
|____More stuff related to user
So, you create a new user in FirebaseAuth, you can find more about it below:
Firebase Custom Auth.
Then, after creating a new user, you create child nodes under your database with the key=userId of your current logged in user.
eg. In your addNote function, the id variable will be equal to
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Currently, you're using Push keys which are generated based on Timestamp, which you won't be able to associate with user unless you add a key inside your note object which stored current username, and then find all the child nodes that contain that username, but in that case, your data won't be organized at all.
Then, after you create a node with userId under your main database, you can then push new notes created by your user inside the userId with the push() function. So your database structure will look like below.
___
|
|__users
|__uniqueUserId
| |__note1
| |__note2
|__uniqueUserId2
|__note1
|__note2
|__note3
Next time whenever you want to fetch user created notes, you log in the user, get his ID, and then find the notes corresponding to that ID.
I don't see how you can fit SharedPreferences in there, before there is also function to cache data offline in Firebase once it is loaded.
Securing the notes:
If you implement the database like I said above, you'll be very easily able to secure your database.
Common Database Rules.
If you implement everything correctly like I told, you'll be able to secure your database with the fourth set of rules from above rules.
Since you are using firebase authentication, then you can retrieve the userId, and create the following database:
notes
userId
note : "todo"
description : "study"
Then you can do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notes");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userId = user.getUid();
ref.orderByKey().equalTo(userId).addValueEventListener(new ValueEventListener() {...}
This way you would retrieve the data of the currently logged in user only.

Android studio recylerview in fragment using data from firestore [duplicate]

This question already has an answer here:
How to display data from Firestore in a RecyclerView with Android?
(1 answer)
Closed 4 years ago.
I am currently developing a mobile app in Android Studio. I have a collection in Firebase firestore called Leagues. When I open a fragment from the navigation drawer, the recyclerview is empty. I have two buttons at the top of the layout, both of which open an alert dialog. When I click on either of the buttons and click on the box to start entering text, the leagues magically appear in the recyclerview! Ideally I would like them to appear when the fragment is first opened. To give a bit more context I have a method which fetches the leagues from the collection in Firebase, but having debugged it I've found that this initially returns an empty list. Only when the edittext box in the alert dialog is pressed does the list fill up. Can anyone think why this might be the case?
Thanks in advance
Edit:
public class LeaguesFragment extends Fragment {
Button buttonCreateLeague;
Button buttonJoinLeague;
View view;
FirebaseFirestore firestore;
private String leagueID;
private String userID;
private String leagueName;
private String username;
TextView textViewMyLeagues;
RecyclerView recyclerView;
private List<Leagues> leaguesList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_leagues, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.leaguesList);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(getContext(), leaguesList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
buttonCreateLeague = (Button) view.findViewById(R.id.buttonCreateLeague);
buttonJoinLeague = (Button) view.findViewById(R.id.buttonJoinLeague);
textViewMyLeagues = (TextView) view.findViewById(R.id.textViewMyLeagues);
firestore = FirebaseFirestore.getInstance();
userID = FirebaseAuth.getInstance().getUid();
firestore.collection("users").document(userID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
username = documentSnapshot.getString("name");
}
}
});
buttonCreateLeague.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
leagueID = CreateLeagueID.randomString(6);
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setMessage("Enter league name");
final EditText input = new EditText(getContext());
alert.setView(input);
alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
leagueName = input.getText().toString().trim();
createLeague(leagueID, leagueName);
addUserToLeague(leagueID, username);
addLeagueToUser(leagueID, userID, leagueName);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled.
}
});
alert.show();
}
});
buttonJoinLeague.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
alert.setMessage("Enter league code");
final EditText input = new EditText(getContext());
alert.setView(input);
alert.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
leagueID = input.getText().toString().trim();
firestore.collection("leagues").document(leagueID).collection("members").document(username).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if(documentSnapshot.exists()) {
Toast.makeText(getActivity(), "Already part of this league", Toast.LENGTH_SHORT).show();
}
else {
firestore.collection("leagues").document(leagueID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot documentSnapshot = task.getResult();
if (documentSnapshot.exists()) {
leagueName = documentSnapshot.getString("leagueName");
addUserToLeague(leagueID, username);
addLeagueToUser(leagueID, userID, leagueName);
}
else {
Toast.makeText(getActivity(), "That league does not exist", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
}
});
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled.
}
});
alert.show();
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
leaguesList = new ArrayList<>();
firestore = FirebaseFirestore.getInstance();
userID = FirebaseAuth.getInstance().getUid();
firestore.collection("users").document(userID).collection("leagues").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if(e != null) {
Log.d(TAG, "Error : " + e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()) {
if(doc.getType() == DocumentChange.Type.ADDED) {
//leagueID = doc.getDocument().getString("leagueID");
//leagueName = doc.getDocument().getString("leagueName");
Leagues leagues = doc.getDocument().toObject(Leagues.class);
leaguesList.add(leagues);
}
}
}
});
}
having debugged it I've found that this initially returns an empty list.
Yes, this the normal behaviour. You cannot use now something that hasn't been loaded yet. With other words, you cannot simply create the leaguesList variable as global variable and use it outside the onEvent() method because it will always be empty due the asynchronous behaviour of this method. This means that by the time you are trying to use that list outside that method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to use leaguesList list only inside the onEvent() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
Maybe the problem is your leaguesList still empty when onCreateView is trigger. And when onEvent from firestore trigger you not notify data set change the adapter.

Data fetched from FirebaseDatabase is getting shown in 3 separate AlertDialogs instead of one

I'm fetching some data from FirebaseDatabase and then putting them into an array and then trying to show them in a List which is in a custom AlertDialog.
Here's the code:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
Here's the database structure:
app
-child
-anotherChild
-yetAnotherChild
-inaccessibleChild
-someChild: "value"
-lol: "value"
I can't use valueEventListener() here as I have no access to inaccessibleChild. The inaccessibleChild here is the uid of the other users who followed a particular user. How can I access there uid?
The problem is that data is getting fetched but instead of getting shown in a list in one AlertDialog, it is getting shown one-by-one in 3 separate AlertDialog.
What is going wrong here?
Please let me know.
Firebase transactions are asynchronous so your initial line to add the 3 children happens after you set your listener, therefore your callback is called 3 times. (making 3 dialogs).
Move this line outside of the on click:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
Then when you add the below listener (inside the on click) it should be ok
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Put limit when you are using valueEventListener or addChildEventListener. like this,
int limit = 100;
databaseRef.child("chats").limitToLast(limit).addValueEventListener(listener);
And always remove listener when you've done with your work related to firebase. like this,
databaseRef.child("chats").limitToLast(limit).removeEventListener(listener);
Thanks.
Create and show the AlertDialog before you call .addChildEventListener()
Then use inside addChildEventListener call notifyDatasetChanged() after you downloaded the appropriate data. Do not create the AlertDialog inside the addChildEventListener
You can use Firebase Queries to limit the data that is downloaded by a listener.
query.orderByChild("someChild").limitToLast(1).addChildEventListener(...
#Blundell has the insight of solving your problem. I just want to suggest you a similar approach with addValueEventListener.
The value event listener will fire once for the initial state of the
data, and then again every time the value of that data changes.
You need to move out the firebase query from onClick function. So your query might look like this..
// Declare the variable names as public
private String names[];
private void addFirebaseListener() {
ref = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
ref. userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
names[] = l.toArray(new String[0]);
// Call notifyDataSetChanged each time your array gets updated
adapter.notifyDataSetChanged();
}
#Override public void onCancelled(FirebaseError error) { }
});
}
Now write a function to show the ListView in the AlertDialog
// Declare the adapter as public and initialize it with null
private ArrayAdapter<String> adapter = null;
private void showListInDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
if(adapter == null)
adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
// Now set the adapter
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
Now inside your onCreate function you need to set the Firebase listener first and then set the onClick function like this.
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListInDialog();
}
});
#Hammad Try this modified code basing on your requirement.
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
AlertDialog alertDialog;
ArrayList<String> l;
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
if(l == null) {
l = new ArrayList<String>();
}
l.add(newD.get("lol").substring(30));
String names[] = new String[l.size()];
for(int length=0; length < l.size(); l++) {
names[length] = l.get(length);
}
if(alertDialog == null) {
alertDialog = new AlertDialog.Builder(Activity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
} ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
if(!alertDialog.isShowing()) {
alertDialog.show();
}
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
}
});
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
/**
Retrieve lists of items or listen for additions to a list of items. This callback is triggered once for each existing child and then again every time a new child is added to the specified path. The DataSnapshot passed to the listener contains the new child's data.
**/
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
ref.addChildEventListener(childEventListener);
Usining ChildEventListener onChildAdded are call per child you have in that node. Means your code runs 3 time so dialog appers 3 time.
This is the problem
So the solution is:
While using a ChildEventListener is the recommended way to read lists of data, there are situations where attaching a ValueEventListener to a list reference is useful.
Attaching a ValueEventListener to a list of data will return the entire list of data as a single DataSnapshot, which you can then loop over to access individual children.
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
inaccessibleChild.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//here you can access the each child of that node.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
Well, none of the above answers really helped, though Linxy's answer is correct, I saw it after solving the probelm.
Moving all the code out and writing just this line: alertDialog.show(); inside setOnClickListener() improving my code to this:
query = mDatabase.child("child").child(anotherChild).child("yetAnotherChild");
query.orderByChild("someChild").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null) {
Map<String, String> newD = (Map<String, String>) dataSnapshot.getValue();
ArrayList<String> l = new ArrayList<String>();
l.add(newD.get("lol").substring(30));
String names[] = l.toArray(new String[0]);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
LayoutInflater inflater = getLayoutInflater();
View convertView = inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("title");
ListView lv = (ListView) convertView.findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, names);
lv.setAdapter(adapter);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
Toast.makeText(getBaseContext(), "NULLLLL", Toast.LENGTH_SHORT).show();
}
}
...
...
});
uProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert11.show();
}
});
Anyway, I would like to thank all those who answered this question.
Peace.

Categories

Resources