get array string from firebase on android - android

I have array list on android it's worked .
in past i was write the array string at the code like :
String[] string = {"st1","st2","st1"}
I was made connection the app to firebase and i was success to get string .
I want to get the string array from firebase, but i don't know how!
i was read about that but not helpful for me.
i was put the strings at the array list as function on Fragment.
so my code is :
private ArrayList<City> initCities() {
Log.d(TAG, "ArrayList_CitiesFragment_initCities");
String[] cityName = {"st1","st2","st3"};
ArrayList<City> theCities = new ArrayList<>();
for (String aCityName : cityName) {
City city = new City(aCityName, false);
theCities.add(city);
}
return theCities;
}
then at the onViewCreate operation the function.
i want it from the firebase.
i don't know how..

You need to add addValueEventListener() method to receive the events whenever there is change in data.
Here is the sample code as you have not mentioned clearly your database structure and what part you want to retrieve.
ArrayList<String> names = new ArrayList<String>;
final DatabaseReference ref = FirebaseDatbase.getInstance().getReferenece().child("Your_Child_Name");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for(Map.Entry<String, Object> entry : ((Map<String, Object>) dataSnapshot.getValue()).entrySet())
{
Map singlet = (Map) entry.getValue();
names.add((String)singlet.get("COLUMN_NAME_OF_DATABASE_YOU_WANT"));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "AWW SNAP... Something is Wrong.", Toast.LENGTH_LONG).show();
}
});

Related

ListView duplicating after adding new items to Firebase [duplicate]

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

How to add Map values in Firebase Realtime Database

I'm creating an app and trying to use Firebase Realtime Database to store the scores for my game. My database has many users, each of which contains a TreeMap with the date as the key and the score as the value. I am trying to have the player click a button and save their score inside the TreeMap. I am having trouble with reading the data in the TreeMap because I want this to be a one time read and not a listener.
I have tried retrieving the map first, updating it, and reuploading it to the database. However, I don't know how to link this to the button click, as online tutorials all seem to use a listener and snapshot.
private void showData(DataSnapshot dataSnapshot){
String name = "";
String age = "";
String number = "";
TreeMap<String, Integer> scores = new TreeMap<>();
for (DataSnapshot ds: dataSnapshot.getChildren()){
User user = new User();
if (ds.child(userID).getValue(User.class).getScores() != null){
ds.child(userID).getValue(User.class).getScores().put(date, totalScore);
scores = ds.child(userID).getValue(User.class).getScores();
}
name = ds.child(userID).getValue(User.class).getUserName();
age = ds.child(userID).getValue(User.class).getUserAge();
number = ds.child(userID).getValue(User.class).getUserPhoneNumber();
}
scores.put(date, totalScore);
User temp = new User(userID, name, age, number, scores);
myRef.child(userID).setValue(temp);
}
This is the solution I had written, but it doesn't incorporate the button click.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapShot.getValue(User.class);
if(user.getScores()!=null){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("date", date);
hashMap.put("totalScore", totalScore);
query.child(userId).setValue(hashMap);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
this is how you update the score , you didnt show ur database schema so i i am not clearly give you the exact query.

Retrieve data under userids from firebase

I'm facing a problem on how to retrieve all data under uids to list string.But I don't know how to pass uids.
Edit
I want to retrieve all data ..I mean there can have many uids and their childs.I want to access all uid(not only my uid but also other uids under mdg node).😪 Please help me...
Create a global ArrayList in your Activity
private ArrayList<User> arrayList = new ArrayList<>();
You need Model class for storing all data.
class User {
private String postText, uploadTime , Uplaoder;
public User(String postText, String uploadTime, String uplaoder) {
this.postText = postText;
this.uploadTime = uploadTime;
Uplaoder = uplaoder;
}
//getter setter here..
}
Then in your Activity
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("msg");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshotMessages : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : snapshotMessages.getChildren()) {
String post_text = snapshot.child("post_text").getValue(String.class);
String upload_time = snapshot.child("upload_time").getValue(String.class);
String uploader_name = snapshot.child("uploader_name").getValue(String.class);
User user = new User(post_text, upload_time, uploader_name);
arrayList.add(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to get all strings from firebase database

I am trying to store all children of my firebase database into an array list.
Here is my database structure:
I am currently trying to loop through children in order to get the values I need as follows:
private void initializeData(int Destination) {
listItems = new ArrayList<>();
DatabaseReference MyRef = FirebaseDatabase.getInstance().getReference("rideShare");
switch (Destination) {
case 0:
Toast.makeText(getActivity(), "LA BUNDLE", Toast.LENGTH_SHORT).show();
MyRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
String NameValue = snapshot.child("Name").getValue(String.class);
String Price = snapshot.child("Price").getValue(String.class);
String Type = snapshot.child("Trip Type").getValue(String.class);
String Date = snapshot.child("Date").getValue(String.class);
String Destination = "LA";
String Phone = snapshot.child("Phone Number").getValue(String.class);
listingItem newItem = new listingItem(NameValue, Type, Price, Date, Destination, Phone);
listItems.add(newItem);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
//Log.w(TAG , "Failed to read value.",error.toException());
}
});
break;
}
}
Add all the string variables into a POJO class and name the variables same as the child nodes keys. Use snapshot.get(listingItem.class) directly instead.
Refer to this https://stackoverflow.com/a/39861649/3860386
To get those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rideShareRef = rootRef.child("rideShare");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<ListingItem> listItems = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nameValue = ds.child("Name").getValue(String.class);
String type = ds.child("Trip Type").getValue(String.class);
String price = ds.child("Price").getValue(String.class);
String date = ds.child("Date").getValue(String.class);
String destination = "LA";
String phone = ds.child("Phone Number").getValue(String.class);
ListingItem newItem = new ListingItem(nameValue, type, price, date, destination, phone);
listItems.add(newItem);
}
Log.d("TAG", listItems);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rideShareRef.addListenerForSingleValueEvent(eventListener);
When you are writting Java code, it's better to use Java Naming conventions. I added this code accordingly.
Also as you probaly see, i have added the declaration of listItems inside onDataChange() method, otherwise it will alwasy be null due the asynchronous behaviour of this method.

Unable to show all the strings retrieved from FirebaseDatabase

I'm trying to retrieve some string from firebase and trying to show them as the entries of an AppCompatSpinner.
Here's how I'm retrieving it:
vDatabase.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
vName = newRequest.get("vName");
Toast.makeText(getBaseContext(), venueName, Toast.LENGTH_SHORT).show();
if (vName != null) {
ArrayList<String> spinnerArray = new ArrayList<>();
spinnerArray.add(vName);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);
venueSpinner.setAdapter(adapter);
} else {
Toast.makeText(getBaseContext(), "v == null", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is that above code is retrieving all the strings but showing only the last fetched string and not all of them.
What's wrong here and how can I show all the strings retrieved from the FirebaseDatabase?
Declare ArrayList spinnerArray = new ArrayList<>(); in your class not inside the onDatachange method
by keeping in onDatachange the variable is creating newly , so everytime new value is inserted in it ,so u are getting the last value to display.

Categories

Resources