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

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.

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

Failing to Read Nested Data From Firebase Database

I am sending "Appetizers and Snacks" which is in name key from one activity 1 to activity 2.
In activity 2,the data received is simply :
intent = getIntent();
String received_id = intent.getStringExtra("cat_id");
Log.e("ID received is", received_id);
Output is :
ID received is : Appetizers and Snacks
With the Help of this value, I'm trying to read the Node recipes and display all the data in their Respective Views.
I only want to know , how can I get to the recipes node. I tried this till now :
query = FirebaseDatabase.getInstance().getReference("All Categories").orderByChild("name").equalTo(received_id);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.e("data", String.valueOf(dataSnapshot));
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("recipes").getChildren()) {
Log.e("data final is ", String.valueOf(dataSnapshot1.getValue()));
DetailModel p = dataSnapshot1.getValue(DetailModel.class);
detailModelList.add(p);
}
detailAdapter = new DetailAdapter(DetailCategory.this, detailModelList);
recyclerView.setAdapter(detailAdapter);
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(DetailCategory.this, "No data available !", Toast.LENGTH_SHORT).show();
Log.e("No data available !", "No data available !");
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(DetailCategory.this, databaseError.getDetails(), Toast.LENGTH_SHORT).show();
}
});
recyclerView.setLayoutManager(new GridLayoutManager(DetailCategory.this, 2));
The Log.e("data", String.valueOf(datasnapshot)) gives this Output :
DataSnapshot { key = All Categories, value = {0={image=https://i.imgur.com/0toOJMa.jpg, recipes={randomkey={image=https://i.ibb.co/gvH8Vp2/5f6fg0l8-keraal-roast-chicken-62.png, servings=4 servings, ingredients="complete Ingredients here"}}, name=Appetizers and Snacks}} }
My DetailModel class is a simple class :
public DetailModel() {
}
String image,title, time,servings,ingredients,steps;
public DetailModel(Integer id, String image, String title, String time, String servings, String ingredients, String steps) {
this.id = id;
this.image = image;
this.title = title;
this.time = time;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
public Integer getId() {
return id;
}
public String getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getTime() {
return time;
}
public String getServings() {
return servings;
}
public String getIngredients() {
return ingredients;
}
public String getSteps() {
return steps;
}
But every time there is no data Received in the App, Completely Blank, even the Else conditions are not executing.
it doesn't reach if (dataSnapshot.exists()) { and none of the code inside is executed. Since, I also checked with settings logs , nothing is found in Logcat as well . Any Tips , why this is happening ?
EDIT : i did as Frank Recommended, Still there is no data in the App
Please Guide me reading this nested Data.
Instead of this:
databaseReference = FirebaseDatabase.getInstance().getReference("All Categories").child("name").orderByValue().equalTo(received_id).getRef();
You'll want to use:
Query query = FirebaseDatabase.getInstance().getReference("All Categories").orderByChild("name").equalTo(received_id);
So:
Use orderByChild("name") to tell the database to order all child nodes on the value of their name property.
Use equalTo(...) to then filter down the sorted data.
Remove the getRef() as that actually undoes all your query buildin.
To then read the data, do:
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot categorySnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot recipeSnapshot: categorySnapshot.child("recipes").getChildren()) {
DetailModel p = recipeSnapshot.getValue(DetailModel.class);
detailModelList.add(p);
}
}
detailAdapter = new DetailAdapter(DetailCategory.this, detailModelList);
recyclerView.setAdapter(detailAdapter);
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(DetailCategory.this, "No data available !", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
}
So:
Listen to the entire query we just created.
Then loop over the children of recipes of each node we get back in the snapshot.
databaseReference = FirebaseDatabase.getInstance().getReference();
val ref = database.child("All Categories").child("0").child("recipes")
val valueEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val recipes = dataSnapshot.getValue(Recipes::class.java) // recipes model reading
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
ref.addListenerForSingleValueEvent(valueEventListener)

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

Edit item under pushed ID from firebase through Android Studio

My goal is to edit the "price" under a pushed ID in my database. My current code does not let me edit it, but instead it creates another pushed ID. How do I edit it and not create not pushed ID? Thanks in advance.
This is my code for editing the data:
String uid = currentUser.getUid();
prodidref = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products");
String prodid = prodidref.push().getKey();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Products");
profdb = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products").child(prodid);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String keyprice = "price";
String valueprice = ETPrice.getText().toString();
DatabaseReference child = profdb.child(keyprice);
child.setValue(valueprice);
}
});
Here's a screenshot from my database:
This is the result of my current code:
If you don't know the key of the product you want to modify, you will need to perform a query find that key. This means that you must know something about the product on which you can query. E.g. if you're trying to set a price of 20 on Broccoli, you can run a query to find the Broccoli and update based on that:
DatabaseReference products = FirebaseDatabase.getInstance().getReference().child("Products");
Query broccolis = products.orderByChild("name").equalTo("Broccoli");
broccolis.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot broccoli: snapshot.getChildren()){
broccoli.getRef().child("price").setValue(20);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException()l
}
});
I hope this help you !
String uid = currentUser.getUid();
String pushKey;
prodidref = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products");
String prodid = prodidref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren())
{
Log.d("kkkk activelink",""+snapshot.getKey());
pushKey = snapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
profdb = FirebaseDatabase.getInstance().getReference().child("Profile").child(uid).child("Products").child(pushKey);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String keyprice = "price";
String valueprice = ETPrice.getText().toString();
DatabaseReference child = profdb.child(keyprice);
child.setValue(valueprice);
}
});

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.

Categories

Resources