Access Firebase database specifics child item - android

I have two children in a Firebase database like 1) Semester I Notes and 2) Semester II Notes.
I have successfully uploaded data into these children, but when I retrieve these items, it just returns the first child's data. Code for Firebase helper here - name is the variable of our Semester I Notes or Semester II Notes
public class FireBaseHelper {
DatabaseReference db;
boolean saved;
String name;
Query myref;
ArrayList<Semester> semesters = new ArrayList<>();
public FireBaseHelper(DatabaseReference db, String n) {
this.db = db;
myref=db.orderByChild("model").equalTo(n);
name = n;
}
public boolean save(Semester s) {
if (s == null) {
saved = false;
} else {
try {
db.child(name).push().setValue(s);
myref=db.orderByChild("model").equalTo(name);
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
saved = true;
}
return saved;
}
public void fetchData(DataSnapshot dataSnapshot) {
Log.i("Getchildcount", String.valueOf(dataSnapshot.getChildrenCount()));
semesters.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Semester semester = ds.getValue(Semester.class);
semesters.add(semester);
}
}
public ArrayList<Semester> retrieve() {
myref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return semesters;
}
}
I call the retrieve method like this
Firebase helper = new FireBaseHelper(db, NameOfDb);
NotesAdapter adapter = new NotesAdapter(this, helper.retrieve());
//this is the list variable noteItem and I set adapter on it
notesItem.setAdapter(adapter);
Model Image of Firebase

You need to use DatabaseReference childItem = mDatabase.child("child_item_name");
Firebase Realtime database Doc

Related

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

I have a problem after I add another table to my firebase database. it gives me following error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type ...
here is my code, which works fine if I have database like this:
and code:
Main activity code:
rvOrder = (RecyclerView) findViewById(R.id.rvOrders);
rvOrder.setLayoutManager(new LinearLayoutManager(this));
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
rvOrder.setAdapter(myAdapter);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
rvOrder.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase helper code:
public class FirebaseHelper {
DatabaseReference databaseReference ;
Boolean saved = null;
ArrayList<Order> orders = new ArrayList<>();
public FirebaseHelper(DatabaseReference databaseReference) {
this.databaseReference = databaseReference;
}
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
private void fetchData(DataSnapshot dataSnapshot) {
orders.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
}
public ArrayList<Order> retrieve() {
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return orders;
}
If I change my code to this (which I saw in this question link to the question ):
in Main activity:
databaseReference= FirebaseDatabase.getInstance().getReference();
to
databaseReference= FirebaseDatabase.getInstance().getReference().child("Orders");
and in firebasehelper:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}
to
System.out.println(dataSnapshot.getValue(Order.class));
Order order = dataSnapshot.getValue(Order.class);
orders.add(order);
then I am able to add another tables to database but I just get only the last item from the Orders table.
I want to add many tables with multiple items into the database and also I want to get all items from the "Orders" table.
Can anybody suggest me anything?
In your first code snippet you read from the root of the database. Since you're trying to read orders, you should read from /Orders instead:
databaseReference= FirebaseDatabase.getInstance().getReference();
firebaseHelper=new FirebaseHelper(databaseReference);
//myAdapter=new MyAdapter(this,firebaseHelper.retrieve());
//rvOrder.setAdapter(myAdapter);
databaseReference.child("Orders").addValueEventListener(new ValueEventListener() {
Now in your onDataChange you can read the orders by looping over them. Since you already do precisely that in FirebaseHelper.fetchData, you can call that method:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
}
Now all that is left is to wire up the data from firebaseHelper.orders to an adapter and the view:
public void onDataChange(DataSnapshot dataSnapshot) {
firebaseHelper.fetchData(dataSnapshot);
myAdapter=new MyAdapter(this,firebaseHelper.orders);
rvOrder.setAdapter(myAdapter);
}
This last step will require that you make FirebaseHelper.orders public, and probably some of the variables must be final.
I think you need to update this method accordingly:
public Boolean save(Order order) {
if (order == null) {
saved = false;
} else {
try {
databaseReference.child("Orders").push().setValue(order);
saved = true;
} catch (DatabaseException e) {
e.printStackTrace();
saved = false;
}
}
return saved;
}
Try to change:
databaseReference.child("Orders").push().setValue(order);
To:
databaseReference.child("Orders").child(order.getId).setValue(order);
Also, to retreive all Orders keep using the enhanced loop:
for(DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getValue(Order.class));
Order order = ds.getValue(Order.class);
orders.add(order);
}

Firebase Datasnapshot values are not getting reflected in associated class object

I am newbie in Firebase. I am trying to fetch data from firebase to object of the related class. The datasnapshot gets the value from Firebase, but the same values are not getting assigned to the object.
Below is my Firebase Structure:
Here is what getting me the problem:
myRef =database.getReference();
myRef.child("Tables").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded( DataSnapshot dataSnapshot, String s) {
Log.v("DS",dataSnapshot.getValue().toString());
Tables values=dataSnapshot.getValue(Tables.class);
Log.v("isAl", values.toString());
int Capacity=values.getCapacity();
String Customer=values.getCustomer();
boolean IsAllocated= values.isAllocated();
Log.v("isAl", String.valueOf(values.isAllocated())+"\t"+Customer+"\t"+Capacity);
String key = dataSnapshot.getKey();
oldKey=key;
mKeys.add(key);
Tables table=new Tables(Capacity,Customer,IsAllocated);
});
}
My Tables Class is as follows:
public class Tables {
private int Capacity;
private String Customer;
private boolean IsAllocated;
public Tables(int capacity, String customer, boolean isAllocated) {
Capacity = capacity;
Customer = customer;
IsAllocated = isAllocated;
}
public Tables() {
}
public int getCapacity() {
return Capacity;
}
public void setCapacity(int capacity) {
Capacity = capacity;
}
public String getCustomer() {
return Customer;
}
public void setCustomer(String customer) {
Customer = customer;
}
public boolean isAllocated() {
return IsAllocated;
}
public void setAllocated(boolean allocated) {
IsAllocated = allocated;
}
}
Here is my BindViewHolder of Adapter Class:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
list=Tlist.get(position);
Log.v("vlist", String.valueOf(Tlist.get(position)));
holder.tabletext.setText("Table");
holder.status.setText(String.valueOf(list.isAllocated()));
}
In values object, I am getting null values. Any help will be appreciated. Thank you in advance.
Change your class variable it uses a case-sensitive you are using small char and your Firebase DB contains capital
change your class to:
public class Tables {
int Capacity;
String Customer;
Boolean IsAllocated;
And use ValueEventListener to get all the records in single bunch
myRef.child("Tables").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Tables values=dataSnapshot.getValue(Tables.class);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Edit 1: you can get value using map try below code
myRef.child("Tables").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Map<String,String> map=(Map<String,String>)postSnapshot.getValue();
String Customer=map.get("Customer");
String IsAllocated= map.get("IsAllocated");
String Capacity= map.get("Capacity");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to fetch the username list in listview in Android from Firebase database?

I have registered and saved users through my app and now I want to fetch the list of usernames as shown below from Firebase database. How do I do it in list view? my database is shown below:
ArrayList<MODELCLASSNAME> Users=new ArrayList<>();
DatabaseReference df=FirebaseDatabase.getInstance().getReference().child("users");
df.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot.getchildren()){
Users.add(dataSnapshot.getValue(MODELCLASSNAME.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Now loop through your arraylist
get your database reference
firebaseDatabase = FirebaseDatabase.getInstance();
mPostDb = firebaseDatabase.getReference("User");
Now query your table
Query query = mPostDb.orderByKey();
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot){
// Do what ever you whatever you want with this user object
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this method:
public void retrieveNames() {
Query myQuery = mDatabase.orderByChild("name").equalTo("INSERT-HERE-A-NAME-FOR-YOUR-SEARCH");
myQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterator iterator = dataSnapshot.getChildren().iterator();
//FOR YOUR DATA STRUCTURE -
while (iterator.hasNext()) {
String image_uri = (String) ((DataSnapshot) iterator.next()).getValue();
String name = (String) ((DataSnapshot) iterator.next()).getValue();
String username = (String) ((DataSnapshot) iterator.next()).getValue();
YourUserObject User = new YourUserObject (image_uri, name, username);
YourArrayList.add(User);
}
YourAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Firebase returning null for Data values in Android

All data.getValue() are returning null. I can get child key to return fine. I can write to firbase fine. Just data.getValue is returning null for some unknown reason. I have other classes working fine using the exact same format.
//method for retrieving info from firebase which has notifications
private void retrieveInfo(){
Firebase ref = new Firebase("https://fitnectapp.firebaseio.com/");
// Attach an listener to read the data at our posts reference
ref.addChildEventListener(new ChildEventListener() {
// Retrieve new posts as they are added to the database
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
getUpdates(snapshot);
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
getUpdates(snapshot);
}
#Override
public void onChildChanged(DataSnapshot snapshot, String previousChildKey) {
getUpdates(snapshot);
}
#Override
public void onChildMoved(DataSnapshot snapshot, String previousChildKey) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
//All data values returning null??
private void getUpdates(DataSnapshot ds) {
if (ds.getKey().equals("notifications")) {
for (DataSnapshot data : ds.getChildren()) {
String user = sp.getString("username", null);
Notification notification = data.getValue(Notification.class);
if(notification.getNotifUser().equals(user)){
String sender = notification.getNotifSender();
String workout = notification.getNotifWorkout();
String notificationTxt = sender + " has liked your workout, " + workout;
notifications.add(notificationTxt);
}
}
}
}

fetch data from google firebase (android)

I use firebase to store data , but I could not get the list of data
from firabse ,Specifically I want to get arraylist of person object.
here is the class person
public class Person {
private String name;
private String username;
public Person() {
}
public Person(String name, String username) {
this.name = name;
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and here is data structure
You can fetch the data with any of the event listeners. Here is with child event listener.
List<Person> persons = new ArrayList<>();
ChildEventListener listener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
persons.add(person);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Person person = dataSnapshot.getValue(Person.class);
persons.remove(person);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseDatabase.getInstance().getReference().child("persons").addChildEventListener(listener);
Ugur B answers also correct one. Here,You can also fetch firebase data by using the ValueEventListener too...
ArrayList<String> arrayListVal = new ArrayList<String>();
fbref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Person person = postSnapshot.getValue(Person.class);
//Adding it to a ArrayList
arrayListVal.add(person);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Failed to fetch data: " + firebaseError.getMessage());
}
});

Categories

Resources