Firebase data read before operation android - android

I have an android app that reads total number of posts. After that a user writes another post then the total number of post is updated. Also stores post with "postno"+totalPost as the key.
But whenever the operation is performed ,it throws a null-pointer exception on postNo.
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Integer postNo=dataSnapshot.child("posts").getValue(Integer.class);
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference("posts").setValue(postNo+1);
DatabaseReference reference = database.getReference("users/postno" + postNo);
reference.setValue(new Post());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MyActivity.this,"Listener Cancelled",Toast.LENGTH_SHORT).show();
}
});

Related

Android - Convert Firebase query result to string

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

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 can I get value from firebase for specific key at specified child without using childEventListener?

I am writing an android app in which I need to retrieve value from Firebase database which I manually added before. The data stored in Firebase database is not symmetrical, which is why I can not use a class object.
I want to do something similar to following codes.
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseRef;
firebaseDatabase = FirebaseDatabase.getInstance();
databaseRef= firebaseDatabase.getReference().child("child").child("child2");
String value = databaseRef.getValue("key");
//In above line I want to retrieve string at child → child2 → key:"value"
While recommended, you don't have to use custom Java classes for getting values out of Firebase. You can also read the primitive types directly, as I'll show below. But no matter whether you use custom classes or primitive types, you will always have to use a listener to read data from the database:
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseRef;
firebaseDatabase = FirebaseDatabase.getInstance();
databaseRef= firebaseDatabase.getReference().child("child").child("child2");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "listener canceled", databaseError.toException());
}
};
You can attach a listener to any level in your JSON tree this way, and Firebase will synchronize all the data below that point into the DataSnapshot. Then you can get it from the snapshot with its getChild() and getValue() methods. So for example to read everything under child, but only print child2:
databaseRef= firebaseDatabase.getReference().child("child");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getChild("child2").getValue(String.class);
Log.i(TAG, "child2: "+value);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "listener canceled", databaseError.toException());
}
};
The second snippet reads more data from the database, but then only extracts child2 from the snapshot.
You need to set ValueEventListener and take a datasnapshot as written in the Firebase documentation
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get Post object and use the values to update the UI
Post post = dataSnapshot.getValue(Post.class);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
mPostReference.addValueEventListener(postListener);

How can I retrieve some fields from my Firebase database before I push any changes to it?

Currently I create a Listing object and store a bunch of fields in there. Two of the fields I need to store are the current User's email and name. I am trying to get those two fields as follows
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After this bit of code I have the line
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
All of this code is called by me pressing a button. The first time I press the button, the entire Listing object is pushed to Firebase just the way I want it EXCEPT the user email and username aren't there because they're blank. The second time I press the button the Strings are there how I want.
My guess is that this is because OnDataChange only executes after I push the Listing object. Is this true? How can I get OnDataChange to execute before I push the listing object?
The listener onDataChange() callbacks are asynchronous. The reason that your email and username is blank is because onDataChange hasn't been executed yet to make sure you push data after email and username are retrieve, put the code inside onDataChange()
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
//set up your l value
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Once you press the button above code should be called to obtain email and username then push the data as you want.
User addValueEvenListener like :
DatabaseReference map = database.getReference("field_name");
map.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
****OR using****
database.getReference("field_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "Field data", dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.e(TAG, "Failed to read user", databaseError.toException());
}
});

goOnline doesn't write data in Firebase database

I am printing some custom messages when user clicks on Button, after printing message on Firebase, just closing connection by using database.goOffline(). Here is my code :
private void print() {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mainRef = database.getReference("messages");
database.goOnline();
mainRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
database.goOffline();
}
#Override
public void onCancelled(DatabaseError databaseError) {
database.goOffline();
}
});
mainRef.child("abcd").setValue("my message " + randomvalue);
}
It is working for first time by calling print(), but if i am calling it multiple times it just print message for first time, rest of the times it is not doing anything.
Can anyone please provide me solution for that?

Categories

Resources