ListView duplicating after adding new items to Firebase [duplicate] - android

This question already has answers here:
Duplicate objects from Firebase loaded into ListView
(2 answers)
Closed 1 year ago.
I am trying to add the teacher to the firebase real-time DB and Retrieving the teachers in the listView as shown in this image:
But when add a new item I get retrieved the existing data twice and new data once as shown in the picture below:
After Adding - Leading the Duplication of the ListView
''' //value variables
ArrayList<teachersHelper> teachersFromdatabase = new ArrayList<>();
teacher_adapter teacher_adapter;
THIS METHOD IS CALLED ON ONCLICK OF ADDTEACHERS
private void addingteacher() {
progressBar.setVisibility(View.VISIBLE);
// opening the Custom dialog to get the information of the new Teachers
Dialog mydialog = new Dialog(teacher_admin.this);
mydialog.setContentView(R.layout.addteachers);
mydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
progressBar.setVisibility(View.GONE);
mydialog.show();
mydialog.setOnDismissListener(dialog -> progressBar.setVisibility(View.GONE));
// hooking all the views of the dialog
EditText teache5rName = mydialog.findViewById(R.id.teacherssname_dialogbox);
EditText registrationNumber = mydialog.findViewById(R.id.teachersReg_dialogbox);
EditText passwordteacher = mydialog.findViewById(R.id.teacherspassword_dialogbox);
EditText department = mydialog.findViewById(R.id.teachersDepartment_dialogbox);
EditText mobilenumber = mydialog.findViewById(R.id.teacherMobilenumber_dialogbox);
NeumorphButton addteachersButton = mydialog.findViewById(R.id.add_teachersDialog);
// when the add button on the dialog is pressed
addteachersButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// dilog and progress bar
progressBar.setVisibility(View.VISIBLE);
//converting the edittext the String Literals
String tnamez = teache5rName.getEditableText().toString().trim();
String tregNu = registrationNumber.getEditableText().toString().trim();
String tpassw = passwordteacher.getEditableText().toString().trim();
String tdepartment = department.getEditableText().toString().trim();
String tmobileNum = "+91" + mobilenumber.getEditableText().toString().trim();
// validating the fields wheather they are empty or not
if (!validateFields(tnamez, tregNu, tpassw, tdepartment, tmobileNum)) {
// if empty then show a error custom dialog
donedialogboxMeathod(false);
progressBar.setVisibility(View.GONE);
return;
}
donedialogboxMeathod(true);
// where the teachers are under so the adding teacher fuction is in admin so
// adminhelper is created and called the function
AdminHelper adminHelper = new AdminHelper();
// adding the teacher
adminHelper.addTEachers(tnamez, tregNu, tpassw, "No", tdepartment,
"No", tmobileNum, "No");
// notifyin the adpater that we added new ber
teacher_adapter.notifyDataSetChanged();
// dissmissing the progressbar and Custom dialog
progressBar.setVisibility(View.GONE);
mydialog.dismiss();
}
});
THIS METHOD IN ADMINHELPER TO ADDTEACHERS
public teachersHelper addteacher(String tName, String tregNumber, String tPassword,String
imageId, String tDepartment,String tEmail, String
tphoneNumber, String tadress) {
// creating the teachers Helper Class
teachersHelper teachersHelpers = new teachersHelper(tName, tregNumber, tPassword, imageId, tDepartment,
tEmail, tphoneNumber, tadress);
// database stuff
DatabaseReference teacherreferenc = FirebaseDatabase.getInstance().
getReference("Admin").child(mAuth.getUid()).child("INSTITUTE");
//adding value
teacherreferenc.child("TEACHERS").child(tregNumber).setValue(teachersHelpers);
return teachersHelpers;
}
RETRIEVING THE TEACHERS AND ADDING THEM TO THE LISTVIEW (i think the problem is here)
public void settingViews(){
// Firebase variables to retreive the data of the teacher
FirebaseAuth mAuth = FirebaseAuth.getInstance();
DatabaseReference databasereference = FirebaseDatabase.getInstance()
.getReference("Admin").child(mAuth.getUid()).child("INSTITUTE")
.child("TEACHERS");
//the teachers are stored with the node of registrationNumber so i created a arraylist
ArrayList<String> registrattionNumber = new ArrayList<>();
// valueevent to retreving the data
databasereference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
// cheching if the snapshot exists
if (snapshot.exists()) {
// getting all the registration Number
for (DataSnapshot regis : snapshot.getChildren()) {
// adding the registrationNumbers to the arraylist
registrattionNumber.add(regis.getKey());
}
// based on the arraylist of the registrationNUmber we will be retriving
// the data of teachers of particular registrartion Number
for (int i = 0; i < registrattionNumber.size(); i++) {
//firebase stuff
Query teacherssdata = FirebaseDatabase.getInstance()
.getReference("Admin").child(mAuth.getUid()).child("INSTITUTE")
.child("TEACHERS").child(registrattionNumber.get(i));
// value evnet listener
teacherssdata.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
// retreiving all the teachers data from the snapshot
String _name = snapshot.child("tName").getValue().toString();
String _regno = snapshot.child("tregNumber").getValue().toString();
String _pass = snapshot.child("tPassword").getValue().toString();
String _img = snapshot.child("image").getValue().toString();
String _depart = snapshot.child("tDepartment").getValue().toString();
String _phonenumber = snapshot.child("tphoneNumber").getValue().toString();
String _adress = snapshot.child("tadress").getValue().toString();
String _emai = snapshot.child("tEmail").getValue().toString();
// creating the teacherclass and adding all the info from the firebase
teachersHelper teachersHelperzzzz = new
teachersHelper(_name, _regno, _pass, _img, _depart, _emai
, _phonenumber, _adress);
// adding the teacher objects to the Golbal Variable
teachersFromdatabase.add(teachersHelperzzzz);
// creating listview
// creating the adapter
teacher_adapter = new teacher_adapter(teacher_admin.this,
teachersFromdatabase);
// setting the adapter to the listview
listView.setAdapter(teacher_adapter);
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
StyleableToast.makeText(teacher_admin.this, "Deleted Sucessfully"
, R.style.exampleToast).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
dialogboxMeathod(teacher_admin.this, error.getMessage());
}
});}

Every time there's a change to databasereference, your onDataChange gets called with a full snapshot of the data at that path. So even if only one child node was changed/added/removed, the snapshot also contains all other (unmodified) child nodes that you already added to registrattionNumber.
The simplest solution is to clear registrattionNumber at the top of onDataChange:
databasereference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
registrattionNumber.clear();
...
Also see:
Duplicate objects from Firebase loaded into ListView
Duplicate data from firebase realtime databse
Item gets duplicated in adapter, when we delete or update item from Firebase Realtime Database
Why do i get duplicate values when adding data to firebase realtime database using kotlin?
And many more from this search: https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bandroid%5D+duplicate

Related

How to Simply retrieve all the items and values in Firebase using Android Studio

Here is my code. I tried to retrieve it in the log then display it if it
is retrieved. But I think it doesn't seem the right way. And hoping someone could correct me, on how to easily retrieve all the items and values in firebase.
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
.child("FirstRoot");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
//
// Map<String,Object> map = (Map<String,Object>) dataSnapshot.getValue();
// Object material = map.get("item");
// Object value = map.get("value");
// int v = Integer.parseInt(String.valueOf(value));
String material = String.valueOf(dataSnapshot.child("item").getValue());
Log.d("Item:", material);
// String item = dataSnapshot.child("item").getValue().toString();;
//// Float valuee = Float.parseFloat(dataSnapshot.child("valuee").getValue().toString());
// entries.add(new PieEntry(13f, item));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Kotlin
If you want to read data from firebase cloud firestore you want to simple write this code.
// Get a Instance from FirebaseFirestore.
val db= FirebaseFirestore.getInstance()
//Get the user current Id.
val uId = auth.currentUser!!.uid
//Instead of XYZ you have to write your collection name and Id in
//document.
db.collection("XYZ").document(uId)
.get()
.addOnCompleteListener {
if (it.isSuccessful){
//When it is successful you have to do what you want as I have given example that you can understand better through this way you can get userName and you can set into your textView and you can read as many data as you can this is one example.
val documentSnapShot = it.result
val firstName = documentSnapShot.getString("first_name")
tv_Set_ProfileName.text =firstName
}
}
Although it is not so clear from the question where you want to store the data retrieved from firebase .This may work..Have a try....
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
.child("FirstRoot");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
final String data1 = (Objects.requireNonNull(dataSnapshot.child("data1").getValue())).toString();
final String data2 = (Objects.requireNonNull(dataSnapshot.child("data2").getValue())).toString();
final String data3 = (Objects.requireNonNull(dataSnapshot.child("data3").getValue())).toString();
final String data4 = (Objects.requireNonNull(dataSnapshot.child("data4").getValue())).toString();
model_class model = new model_class(data1,data2,data3,data4);
//do whatever you want with your data
entries.add(new PieEntry(13f, data1));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
}

Not Allowing users Add same Named Child Firebase Android?

I was Trying to add childs(Programmes) to the Above reference STUDENTS.
So the issue is when I retrieve the keys and add them to the ArrayList of Strings.
And check Whether it Matches the entered Text it gives ;
Like Example; in the photo, we have Three Programmes bps,cs,mm.
it gives me matches, not matches,not matches result
what I want is whether it matches or not like as above.
CODE
// retreiving the edittext to String
String prnamez = programmeName.getEditableText().toString().trim().toLowerCase();
// checking if the program already exists
FirebaseAuth autha = FirebaseAuth.getInstance();
DatabaseReference dnn = FirebaseDatabase.getInstance()
.getReference("Admin").child(autha.getUid()).child("INSTITUTE")
.child("STUDENTS");
// arraylist to add the keys of the programme
ArrayList<String> pgName = new ArrayList<>();
// value event listener
dnn.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
progressBar.setVisibility(View.VISIBLE);
// going through all the keys and adding them to the arraaylist of pgName
for (DataSnapshot regis : snapshot.getChildren()) {
// retrieved the programme Name
pgName.add(regis.getKey().toString());
}
// going through the lenght of the array list
for (int i = 0; i < pgName.size(); i++) {
// if the entered programme matches already existing programme name
// then show this custom Toast
if (pgName.get(i).equals(prnamez)) {
// custom Toast
StyleableToast.makeText(Programme_students.this,
"Matches", R.style.exampleToast).show();
} else {
StyleableToast.makeText(Programme_students.this,
"not Matches", R.style.exampleToast).show();
// WANT TO ADD NEW PROGRAMME IN THIS CASE
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});

How to compare two different Firebase database child data items t

I am trying to implement a functionality in my app such that if the user chooses a restaurant, a list of items that are available in the restaurant are displayed and if there are none, it displays a text and a button.
I went about it like this:I would compare two child items, the restaurant names to check if they are equal.If they are, it displays a recyclerview with a list of the items available.
Here's a screenshot of my firebase database
Here's the code snippet of how I save to the FoodRequestRest database child
requestPlceTxt = placeTxt.getText().toString();
System.out.println("First instance of Request place her : " + requestPlceTxt);
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
// String id = UserReqPlaceRef.push().getKey();
Request request = new Request(requestPlceTxt);
// save to database
UserReqPlaceRef.child("Food Request Restaurant")
.child(userID)
.push()
.setValue(request);
Here's the code snippet of how I retrieve the database and display it on the recycler view
// Initialize FirebaseAuth
mFirebaseAuth = FirebaseAuth.getInstance();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.dummyfrag_scrollableview);
noItemsTxt = (TextView) findViewById(R.id.no_items);
OkExitBtn = (Button) findViewById(R.id.ok_exit);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
final List<Donation> donationList = new ArrayList<Donation>();
final DonationAdapter adapter = new DonationAdapter(donationList, this);
recyclerView.setAdapter(adapter);
noItemsTxt.setVisibility(View.GONE);
OkExitBtn.setVisibility(View.GONE);
final String curtUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference rootRef = database.getReference();
// get key for each restuarant chosen to make a donation
final String donateId = rootRef.child("All Donations").getKey();
// get key each restuarant chosen to make a request
final String requestId = rootRef.child("Food Request Restaurant").child(curtUserId).getKey();
final Query latestQuery = rootRef
.child("All Donations")
// .child(curtUserId)
.orderByKey()
.limitToFirst(50);
final DatabaseReference reqRestLoc = rootRef
.child("Food Request Restaurant")
.child(curtUserId)
.child(requestId);
// code here to retrieve the string value located at reqRestLoc
// then compare it with donateRest
// make another value event listener and get the string?
latestQuery.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
donationList.clear();
for (DataSnapshot gigSnapshot : dataSnapshot.getChildren()) {
Donation donation = gigSnapshot
.getValue(Donation.class);
donationList.add(donation);
adapter.notifyDataSetChanged();
String donateRest = (String) dataSnapshot
.child("All Donaations")
.child(donateId)
.getValue();
Log.d(donateRest, "This is the ");
if (s.equals(donateRest)) { // s is the string value gotten from the restReqLoc
recyclerView.setVisibility(View.VISIBLE);
noItemsTxt.setVisibility(View.GONE);
OkExitBtn.setVisibility(View.GONE);
OkExitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DisplayItems.super.onBackPressed();
}
});
}
else {
recyclerView.setVisibility(View.GONE);
noItemsTxt.setVisibility(View.VISIBLE);
OkExitBtn.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have tried different ways of comparing the two strings but I do not have access to both of these data items at the same time, it's either I make a reference to the child of All Donations or FoodRequestRestuarant. Is there a way I can do this?

How do I display list of only registered contacts(on firebase) from a client's address book(via phone numbers)

What I want to do is search through client's address book(phone numbers) and only display contacts who are registered on firebase by looking if their phone numbers are registered.(kind of like Whatsapp)
Currently I am displaying all the registered users on firebase
Code:
public class Tab1 extends Fragment {
private static final String TAG = "MyActivity";
private Button signOut;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
ListView listView;
private DatabaseReference mDatabase;
String userID;
ArrayList<String> userNames = new ArrayList<>();
ArrayList<String> uid = new ArrayList<>();
String receiverUID,receivername;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab1, container, false);
//get firebase auth instance
auth = FirebaseAuth.getInstance();
//get current user
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
}
};
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
mDatabase.keepSynced(true);
listView = (ListView) v.findViewById(R.id.listview);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//User user = dataSnapshot.getValue(User.class);
//Get map of users in datasnapshot
collectUserNames((Map<String, Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Error in Reaching Database
Log.d("TAB1","tab1 error");
}
} );
//Getting username from listview
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String s =Integer.toString(position);
receiverUID = uid.get(position);
receivername = userNames.get(position);
Toast.makeText(getContext(),s , Toast.LENGTH_SHORT).show();
Log.v("log_tag", "List Item Click");
NewReminder();
}
});
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return v;
}
private void collectUserNames(Map<String, Object> users) {
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Getting UID of every user and adding to the Array
String Key = entry.getKey();
Log.d("KEy Value",Key);
//Removing the Current User's ID from the Display List
if(!Key.equals(userID)) {
uid.add(Key);
//Get usernames and append to list and array
userNames.add((String) singleUser.get("username"));
}
//Display all usernames
ArrayAdapter adapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, userNames);
listView.setAdapter(adapter);
}
}
Find my current Firebase Database Model
Here
First of All you have to get the all contacts from clients device,
Note : You Have to Check For Contacts Permissions by your self & don't Forgot to add Permissions in Manifest.
Call initData() in onCreate or After Checking Permissions.
here is the code to get Contacts from Clients Device.
private void initData() {
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
while(Objects.requireNonNull(cursor).moveToNext()){
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Finds the contact in our database through the Firebase Query to know whether that contact is using our app or not.
findUsers(number);
}
}
While Getting Each Contact one by one from clients device, simultaneously we will trigger the firebase query to check whether that contact is using our app or not.
So we are using "findUser" Method to check whether that contact is using our app or not.
private void findUsers(final String number){
Query query = FirebaseDatabase.getInstance().getReference()
.child("User")
.orderByChild("phone")
.equalTo(number);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getValue() != null){
Map<String, Object> map = (Map<String, Object>) snapshot.getValue();
// this will print whole map of contacts who is using our app from clients contacts.
Log.d("ContactSync", snapshot.getValue().toString());
// so you can use any value from map to add it in your Recycler View.
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("ContactSync", error.getMessage());
}
});
}
Here is how my database structure looks like.
Thanks for reading this answer,
I hope this will be helpful!

Write multiple items to firebase in Android

I've written an android app using Firebase as the backend. My problem is only one item can be stored in Firebase and when I try to write more data it replaces the existing data. I want to write multiple bits and data and retrieve them in a list view or something.
My Code is below:
public class Capture_Meetings extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAddress;
private EditText editDateTime;
private TextView textViewPersons;
private Button buttonSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture__meetings);
Firebase.setAndroidContext(this);
buttonSave = (Button) findViewById(R.id.buttonSave);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAddress = (EditText) findViewById(R.id.editTextAddress);
editDateTime = (EditText) findViewById(R.id.editDateTime);
textViewPersons = (TextView) findViewById(R.id.textViewPersons);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating firebase object
Firebase ref = new Firebase(Config.FIREBASE_URL);
//Getting values to store
String name = editTextName.getText().toString().trim();
String address = editTextAddress.getText().toString().trim();
String DateTime = editDateTime.getText().toString().trim();
//Creating Person object
final MeetingUser person = new MeetingUser();
//Adding values
person.setName(name);
person.setAddress(address);
person.setDateTime(DateTime);
//Storing values to firebase
ref.child("Person").setValue(person);
//Value event listener for realtime data update
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
MeetingUser person = postSnapshot.getValue(MeetingUser.class);
//Adding it to a string
String string = "\n Name of School: "+person.getName()+"\n Date:"+ person.getDateTime()+"\nMeeting Notes: "+person.getAddress()+"\n\n";
//Displaying it on textview
textViewPersons.setText(string);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
}
Have a look at the Firebase documentation. You can use the push method to append data to a node, which will have a unique id.
in Firebase you can not store many items/values under one child. But, you can make as many childs (children) with a single value as you want. Just make childs with tags s.a. "address" and "name" with their respective values.
To avoid overwriting of data we can use push() method in following way-
from your code -
ref.child("Person").setValue(person);
just put push() before setValue() method, that is -
ref.child("Person").push().setValue(person);
It will avoid overwriting and it will create a unique id for each data you store under the Person.

Categories

Resources