How to get all strings from firebase database - android

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.

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
}
}

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) {
}
});

get array string from firebase on 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();
}
});

Can't convert object of type java.lang.String to type User

databaseQuestion = FirebaseDatabase.getInstance().getReference("users").child(KrgDOh_GnwpIons_r9Q);
databaseQuestion.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// System.out.println("VAL"+dataSnapshot.getValue());
//clearing the previous artist list
usersQuestions.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//iterating through all the nodes
//getting artist
System.out.println("VAL"+postSnapshot.getValue());
User user = postSnapshot.getValue(User.class);
//adding artist to the list
usersQuestions.add(user);
}
//creating adapter
QuestionUserList userQuestionsAdapter = new QuestionUserList(getActivity(), usersQuestions);
//attaching adapter to the listview
questionsList.setAdapter(userQuestionsAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am facing the following error
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type
I want to fetch the data and display it in Listview. Please help out.
Assuming that users node is the direct child of Firebase root, to get those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String question = ds.child("question").getValue(String.class);
String userId = ds.child("userId").getValue(String.class);
Log.d("TAG", address + " / " + question + " / " + userId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
Having those values, you can create a new object of your class as add it to questionsList list. Also don't forget to declare that list inside the onDataChange() method, otherwise it will be null.
Hope it hels.

How to retrieve user details by user id inside for loop?

I have structured my firebase database like this:
And this is the way how i would structure my tables in database with SQL if i want to fetch user details by passing id as parameter.
But this is not working as i expected.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()) {
final String taskName = snapshot.child("name").getValue(String.class);
final String assignedUserId = snapshot.child("assignedUserId").getValue(String.class);
final String categoryId = snapshot.child("categoryId").getValue(String.class);
final Boolean completed = snapshot.child("completed").getValue(Boolean.class);
final String priority = snapshot.child("priority").getValue(String.class);
User user = getUser(assignedUserId);
ProjectTask projectTask
= new ProjectTask(snapshot.getKey(), dataSnapshot.getKey(), taskName, assignedUserId, priority, completed, categoryId, user);
mProjectTaskList.add(projectTask);
}
for (Category category : mCategories) {
mProjectTasksSection = getTasksWithSection(category);
if (mProjectTasksSection.size() > 0) {
mSectionedRecyclerViewAdapter.addSection(new ProjectTaskListAdapter(R.layout.lst_todo_item_v2, mProjectTasksSection,
category, getActivity()));
}
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerProjectTasks.setLayoutManager(linearLayoutManager);
recyclerProjectTasks.setItemAnimator(new DefaultItemAnimator());
recyclerProjectTasks.setAdapter(mSectionedRecyclerViewAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here i have fetched all tasks and now i just need one more parameter and that is user details, but i really don't know how to get it. I'm not really sure if this is the right way. Maybe it would be easier if i store user name instead of user id. Below i will post my code trying to fetch user details by id:
private User getUser(String keyId) {
DatabaseReference databaseReference = AppController.getInstance().getDatabase()
.getReference().child("users").child(keyId);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return null;
}
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
//pass name here that you want to
// if(postSnapshot.getKey().equals("name".equalsIgnoreCase(nameStr)))
//compare
if(postSnapshot.getKey().equals("name"))
{
final String taskName = snapshot.child("name").getValue(String.class);
//taskName =postSnapshot.getValue().toString();
}
}
Please see this post.
Your DatabaseReference is correct but you don't need to use getChildren() method on the 'dataSnapshot`. Just remove the second iteration. You code should look like this:
public void onDataChange(final DataSnapshot dataSnapshot) {
final String taskName = snapshot.child("name").getValue(String.class);
final String assignedUserId = snapshot.child("assignedUserId").getValue(String.class);
final String categoryId = snapshot.child("categoryId").getValue(String.class);
final Boolean completed = snapshot.child("completed").getValue(Boolean.class);
final String priority = snapshot.child("priority").getValue(String.class);
User user = getUser(assignedUserId);
ProjectTask projectTask = new ProjectTask(snapshot.getKey(), dataSnapshot.getKey(), taskName, assignedUserId, priority, completed, categoryId, user);
mProjectTaskList.add(projectTask);
}
Hope it helps.

Categories

Resources