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) {
}
});
Related
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)
I need a help in firebase database,
I am willing to create an app for a city like Kolkata, to find buses between different local stations, I want to save the data in database and user will input where to where they want to go, after clicking on search, list of available data will be shown,
But I need help in how should I save the data to fetch it easily with less complicated code.
You can save data easily with firebase
private void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
You can search from firebase like below
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("users").orderByChild("name").equalTo("Fazal");
query.addValueEventListener(valueEventListener);
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
//TODO get the data here
User user = dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
};
EDIT:
Firebase dont have a great SQL like searches built in. You can either sort by values/key or you can equalto
https://firebase.google.com/docs/database/android/retrieve-data
for further details check fire-base documentation
https://firebase.google.com/docs/database/android/read-and-write
when you write data into firebase database used below code ..
make pojo class for insert data..
public class City {
public String name, code;
public City(String name, String code) {
this.name = name;
this.code = code;
}
}
then after when you insert data into firebase used below code..
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
mFirebaseDatabase = mFirebaseInstance.getReference("usersDb/UserTable");//define your database name and table name
}
// below method used insert data..
private void insertData(){
City city=new City("Ahmedabad","380016"); // you can add data also runtime.
mFirebaseDatabase.child(city.name).setValue(user);
}
// below method used to search data..
private void sqlQuery(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("usersDb").child("UserTable").orderByChild("name").equalTo("vikas#gmail.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
Log.d("Value::",issue.getValue(User.class).email);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
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.
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.
I've searched a lot of posts in order to find a solution, but i couldn't find one.
I have 2 classes a Recipe class:
public class Recepta {
private String nom;
private List<Ingredient> ingredients;
private List<String> pasos;
public Recepta() {
}
public Recepta(String nom,List<Ingredient> ingredients, List<String> pasos) {
this.nom = nom;
this.ingredients = ingredients;
this.pasos = pasos;
}
//Getter and setters
}
and my Ingredient class:
public class Ingredient {
private String nom;
private String quantitat;
public Ingredient(){
}
public Ingredient(String nom,String quantitat){
this.nom = nom;
this.quantitat = quantitat;
}
//Getter and setters
}
And my DB's structure :
3ER2U0QSDTMHRdKA0eO231UCQeY2
8eJaHRU9f5ZrVogqhx0Hj1iFcgG2
-jdhd
-ingredients
-0
-nom: "bdhd"
-quantitat: "b,bzh"
-nom:"jdhd"
-pasos
-0: "djdjjd"
-jdjd
-jdjdvshs
AfcGeBzvdLRq19J3kRk3CVg30np2
fk39ClAVaQNFQCONU9Agp0KfUUf1addclose
As you can see, "pasos" is a List of String and "ingredients" is a List of Ingredient.
What I can't find out is how can I retrieve those lists from database as I want to get a List of Recepta.
I've tried a lot of things but all were wrong as it didn't retrieve any of the lists.
That's what I've tried, but i know that doesn't work because Firebase DB doesn't store lists as a List
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference listReference = FirebaseDatabase.getInstance().getReference(user.getUid());
listReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(final DataSnapshot listSnapshot: dataSnapshot.getChildren()){
receptas.add(listSnapshot.getValue(Recepta.class));
}
listReceptaAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I also know that FB DB work with HashMaps but i dont know how to retrieve them or pass from a hashmap to a list without having to go through every position of hashmap
So what should I do? Thank you in advance
I think the below example would help to integrate two data in one list in firebase database
public static ArrayList<MuteModel> muteModelList;
public void updateMuteListServer(){
DatabaseReference frndMuteRef = FirebaseDatabase.getInstance().getReference().child("users/" + getFirebaseUser().getUid().trim() + "/friendlists");
Query queryRef = frndMuteRef.orderByChild(MUTE).equalTo(YES);
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<HashMap<String,MuteModel>> t= new GenericTypeIndicator<HashMap<String,MuteModel>>() { };
HashMap<String,MuteModel> hashMap= (HashMap<String,MuteModel>)dataSnapshot.getValue(t);
if(hashMap!=null) {
muteModelList = new ArrayList<MuteModel>(hashMap.values());
for (MuteModel muteModel: muteModelList){
muteModel.setIsgroup(NO);
}
}else{
muteModelList = new ArrayList<MuteModel>();
}
findGroupMuteList();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void findGroupMuteList() {
DatabaseReference groupMuteRef = FirebaseDatabase.getInstance().getReference().child("users/" + getFirebaseUser().getUid().trim() + "/"+GROUPS);
Query queryRef = groupMuteRef.orderByChild(MUTE).equalTo(YES);
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<HashMap<String,MuteModel>> t= new GenericTypeIndicator<HashMap<String,MuteModel>>() { };
HashMap<String,MuteModel> hashMap= (HashMap<String,MuteModel>)dataSnapshot.getValue(t);
ArrayList<MuteModel> properties;
if(hashMap!=null) {
properties = new ArrayList<MuteModel>(hashMap.values());
for (MuteModel muteModel:properties){
muteModel.setIsgroup(YES);
}
}else{
properties = new ArrayList<MuteModel>();
}
MyChat.muteModelList.addAll(properties);
Gson gson = new Gson();
String strMuteList = gson.toJson(MyChat.muteModelList);
editSharedPref(MUTELIST,strMuteList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
in your case I think the generic adapter of ingredients will look like as follows
GenericTypeIndicator<ArrayList<Ingredients>>
& in case of pasos you can do like
GenericTypeIndicator<ArrayList<Strings>>