Android - Convert Firebase query result to string - android

I'am trying to store the query result in a String variable, but the result I'm getting is the string conversion of the query object.
tableDatabaseReference = FirebaseDatabase.getInstance().getReference("tables");
tableNameQuery = tableDatabaseReference.child("tableName").orderByChild(tableID).equalTo("123");
String tableName = tableNameQuery.toString();
Any suggestions?
EDIT:
Database structure:
Tables:
-------TableID:
--------------TableName:
--------------TableID:

To retrieve data from Firebase Realtime database , you have to add a valueEventListener to your database reference variable like this
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dataRef = database.getReference("YOUR_DATABASE_REF");
dataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// here you can get your data from this snapshot object
String data = dataSnapshot.getValue("CHILD_NAME_HERE").toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get data once you can use singleValueEventListener
dataRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// here you can get your data from this snapshot object
String data = dataSnapshot.getValue("CHILD_NAME_HERE").toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

Firebase operation is asynchronous, so you have to wait to complete the operation to get result. To access data outside of onDataChange you can use LiveData and observe it outside. When you get data inside onDataChange then notify LiveData by posting value. Check below:
private MutableLiveData<String> tableName = new MutableLiveData<>();
DatabaseReference tableDatabaseReference = FirebaseDatabase.getInstance().getReference("tables");
tableDatabaseReference
.child(tableID)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String data = dataSnapshot.child("tableName").getValue(String.class);
//Now post that value to LiveData
tableName.postValue(data);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Observe data here
tableName.observe(this, name -> {
// use name here
});

Related

Firebase Android - Able to write data to Realtime Database but not read back

I am writing to the realtime database in a method using
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Test");
myRef.setValue("test");
Database structure
Later on I am trying to retrieve this string in another method using
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Test");
ValueEventListener valueEventListener = myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
value = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
I want value to read "test" but it always returning null.
Use this technique to resolve your issue
mRef=FirebaseDatabase.getInstance().getReference().child("Test")
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
value = dataSnapshot.getValue(String.class);
Log.d("yourtag ", " Result= "value);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mRef.addValueEventListener(listener);

How to Read Data From Firebase database

I want to read data from my Firebase database for all questions. For e.g. for question1 I want to store ques,ans and answeredBy into three variables. What I am currently doing is here.
private FirebaseDatabase database=FirebaseDatabase.getInstance();
private DatabaseReference
quizRef=database.getReference("Quiz").child("Questions");
quizRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds:dataSnapshot.getChildren())
{
ModelClass modelClass=new ModelClass();
modelClass.setQues(ds.child("question1").getValue(ModelClass.class).getQues());
modelClass.setAns(ds.child("question1").getValue(ModelClass.class).getAns());
textViewQuestionText.setText(modelClass.getQues());
}
}
#Override
public void onCancelled(DatabaseError error) {
textViewQuestionText.setText("Error occurred");
}
});
Tried and Tested. You dont have to check for keys like question1,question2 etc
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference("Quiz/Questions");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ModelClass modelClass = (ds.getValue(ModelClass.class));
modelClass.getAns();
modelClass.getQes();
// fetch any key value pair
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I recommend to use firebase generated hash keys instead of your own keys like question1,question2 etc
Check this
You can just use the data from your Firebase Database directly using the following code:
DatabaseReference q1Ref = quizRef.child("question1");
q1Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String question = dataSnapshot.child("ques").getValue(String.class);
String answer = dataSnapshot.child("ans").getValue(String.class);
int ansBy = dataSnapshot.child("answeredBy").getValue(Integer.class);
// now you can do what you want with the values stored in the variables
}
#Override
public void onCancelled(DatabaseError error) {
textViewQuestionText.setText("Error occurred");
}
});
To read or write data from the database, you need an instance of DatabaseReference:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
To read data at a path and listen for changes, use the addValueEventListener() or addListenerForSingleValueEvent() method to add a ValueEventListener to a DatabaseReference.
You can use the onDataChange() method to read a static snapshot of the contents at a given path, as they existed at the time of the event.
For more information you can refer to firebase docs

Firebase Query returned as a Java class

I have a class Person and I'm trying to query Firebase Database by key (which is equal to subjectId in the code below) and save the value returned to an object of type Person.
Here's my code so far-
private void myFunction(final String subjectId) {
Query query = mDatabaseRef.orderByKey().equalTo(subjectId); //I need to use query
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Person newPerson = dataSnapshot.getValue(Person.class); //?? How to use query's value instead
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How to access one key of JSON tree from Firebase Realtime Database?

I want to get the value of 'caste' key from the JSON tree in Firebase Realtime Database.See this image
I have the user's unique ID and all my auth and user objects are in place. How do I get a reference to only the 'caste' key into a String variable?
Thanks,
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("project-android-536f3");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
String caste = (String) messageSnapshot.child("caste").getValue();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I figured it out. I never provided the unique User ID so it never got data from the database.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(firebaseUser.getUid()).child("caste");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
caste = dataSnapshot.getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase always returning all the rows

I am querying on firebase to fetch data from last point which was previously fetched but it is always giving all the rows.
Code:
Query query = null;
query = mFirebaseDatabaseReference.orderByKey();
String lastKey = getLastKey();
if (!TextUtils.isEmpty(lastKey)) {
query.startAt(lastKey);
}
Please help
DatabaseReference databaseReference = Firebase.getInstance().getReference();
Query lastQuery = databaseReference.child("NODE_NAME").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// you can get last node values..
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Handle possible errors.
}
});
// where NODE_NAME is the root of all these child keys.

Categories

Resources