I want to pass data from one activity to another, first I download it from Firebase Realtime Database and then pass it to another activity and how to use it in it.
my data like this.(image from the internet)
cam_firebase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NotNull DataSnapshot dataSnapshot, String s) {
// long count = dataSnapshot.getChildrenCount();
double longt = dataSnapshot.child("longt").getValue(Double.class);
double lat = dataSnapshot.child("lat").getValue(Double.class);
String type = dataSnapshot.child("type").getValue(String.class);
List<Model> list = new ArrayList<>();
list.add(new Model());
list.get(0).setLat(lat);
list.get(0).setLongt(longt);
cameras_info.onCallback();
}
#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(#NonNull #NotNull DatabaseError error) {
}
});
Assuming that pXGb...lGE2 is the UID of the logged-in user, to be able to read the data that corresponds to your schema, then please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("ProgressReportss").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
for (DataSnapshot ds : snapshot.getChildren()) {
String content = ds.child("content").getValue(String.class);
String timestamp = ds.child("timestamp").getValue(String.class);
String title = ds.child("title").getValue(String.class);
Log.d("TAG", content + "/" + timestamp + "/" + title);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Test 2/30-11-2018/Test 2
Test 3/30-11-2018/Test 3
Test 4/30-11-2018/Test 4
That's how you read it. If you need to send the data to another activity, inside the onComplete() use the logic in the following answer:
How to pass an object from one activity to another on Android
Related
I have a problem i get value from Firebase, but the email only fills up after activity run second time.
private ArrayList<String> currentList = new ArrayList<>();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("userTable").child(user.getUid()).child("Container");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
First time size = 0;
Second time = 3(true result);
update UI after getting response.hope now it will work fine for you
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
//Toast.makeText(getContext(), currentList.size(),
// Toast.LENGTH_LONG).show();
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase listener is async, which means it will run in the background and not stop the code until you recieve a response.
In your code you don't wait for the value to be returned from the server, that why size=0.
what you need to do is check the size inside the listener and after the for loop :
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String string = childDataSnapshot.getKey();
currentList.add(string);
}
String size = String.valueOf(listCurrent.size());
firstNameOfCurrentList.setText(size);
This way you will wait for the value to be returned from firebase and then get the list size.
I want to read from the firebase real time database and set retrieved data in a textview, here is what I have tried so far.
private DatabaseReference buckybarnz;
.........
buckybarnz = FirebaseDatabase.getInstance().getReference().child(userID).child("chel_sea");
ValueEventListener eventListener = buckybarnz.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
if (dataSnapshot1 != null) {
DRive dRive = dataSnapshot1.getValue(DRive.class);
if (dRive != null) {
String receipt = dRive.getExt_ref().trim();
String text = dRive.getTxt_Ref().trim();
chalwe.setText(text);
johns.setText(receipt);
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Nothing is working, even when there's data in the database nothing happens to the textviews.
Please help, what is the best way to solve this problem, even a solution using the string class method would be beneficial. Below is a view of my database this is a view of my database, BSQ.... being the userID]1
I have accessed the database in a different way compared to you :
Firebase.setAndroidContext(this);
Firebase reference1 = new Firebase("https://project-id.firebaseio.com/messages/"); //replace project-id by your project-id
reference1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("reference4: data snapshot key"+dataSnapshot.getKey()+"");
//your code
}
#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(FirebaseError firebaseError) {
}
});
Hope this helps
First of all you don't have to write the for loop, and this should be your edited code in the onChildAdded() method of my code :
if (dataSnapshot != null) {
DRive dRive = dataSnapshot.getValue(DRive.class);
if (dRive != null) {
String receipt = dRive.getExt_ref().trim();
String text = dRive.getTxt_Ref().trim();
chalwe.setText(text);
johns.setText(receipt);
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
} else {
String a = "no pending refunds available";
anthony.setText(a);
chalwe.setText(a);
johns.setText(a);
}
}
Hope this works
I am using firebase real-time database to store and retrieve data but for some reason, I am unable to achieve what I want.
I want to get 20 records at a time on swipe refresh layout.
My data looks like:
Initially, I load 50 records:
chat.limitToLast(default_num_of_messages).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("MAP", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
Log.d("CHAT MSG", chat_message.toString());
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
after these on refresh, I want to load 20 more. I am trying to do something like these. but it does not seem to return.
#Override
public void onRefresh() {
if(refresh_toggle) {
swipe_view.setRefreshing(true);
Log.d("CHAT", "REFRESHED!!!");
//reload new data
chat.orderByChild("timestamp").endAt(10).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map map = dataSnapshot.getValue(Map.class);
String user_id = map.get("user_id").toString();
String message = map.get("message").toString();
String timestamp = map.get("timestamp").toString();
Log.d("CHATS", map.toString());
ChatMessage chat_message = new ChatMessage();
chat_message.setUser_id(user_id);
chat_message.setMessage(message);
chat_message.setTimestamp(Long.parseLong(timestamp));
swipe_view.setRefreshing(false);
if(Integer.parseInt(user_id) == Utils.getInstance().getLoggedInUser().getId()) {
addMessageBox(chat_message, 1);
}
else{
addMessageBox(chat_message, 2);
}
}
#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(FirebaseError firebaseError) {}
});
}
}
As you can see I am trying to orderByChild "timestamp" and then tried different combination of startAt(), endAt() but nothing seem to work.
Try this:
int number_item_load = 10; //changed number if you want
public void loadMore(int offset, String theLastValue) {
// theLastValue: depend on your orderByChild() 's value
mDatabase = FirebaseDatabase.getInstance().getReference().child(Utils.FB_ROOT);
mEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (isAlreadyAttach()) {
// Get your item and callback to view and insert to listView
}
} ...
};
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// TODO Finished loaded number_item_load item
OnLoadedFinish(); //
mDatabase.removeEventListener(mEventListener); // Remove listener after load
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mDatabase.orderByChild("yourvalue").startAt(theLastValue).limitToFirst(number_item_load ).addChildEventListener(mEventListener);
}
It worked perfectly in my case. Goodluck
I have this structure in my Firebase Real-time database :
How can I count the data and show it in my app, which listener shall I use to get all childrens?
There are a few ways in which you could achieve this.
I use the following way:
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
YourObject object = dataSnap.getValue(YourObject.class);
// Use your object as needed
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dataSnapshot returns the child referenced. Once you have it, all you have to do is iterate through them and you have access to "all children" as you wanted.
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
/** Qty of data in demografi, this is what you want. */
long Count = dataSnapshot.getChildrenCount();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you want to monitor the count of data in realtime way,
you have to replace [addListenerForSingleValueEvent] with [addValueEventListener].
I will prefer this way -
String email, gender, nama;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("demografi");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// To get children count
dataSnapshot.getChildrenCount();
email = dataSnapshot.child("email").getValue().toString();
gender = dataSnapshot.child("gender").getValue().toString();
nama = dataSnapshot.child("nama").getValue().toString();
// and so on..
}
#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) {
}
});
If you don't have a model class, you can simply use the String class. So to get all child's data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference demografiRef = rootRef.child("demografi");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama = ds.child("nama").getValue(String.class);
Log.d("TAG", nama);
}
Log.d("TAG", String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
demografiRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be all the names of all your users. As you can see, there is a second log statement which will print the total number of your children.
cBankRef=myRef.child("user_id").child("ASSETS");
cBankRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.child("1").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is"+value);
if(dataSnapshot.child("2").exists()) {
String valuess = dataSnapshot.child("3").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: " + valuess);
}
if (dataSnapshot.child("3").exists()) {
String values = dataSnapshot.child("1").child("description").getValue(String.class);
Log.d(TAG, "onChildAdded: the cash at bank is: "+values);
}
}
#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) {
}
});
first i accessed the user_id child and the ASSETS then through the nodes ("1"),("2") i had to add other nodes in order to get the value, the("1") and ("2") were ("Cash at Bank") ("stock") in the beginning but i decided to change them to numbers but it's giving null #makrand pawar
You have multiple issues in your example:
Your cBankRef is pointing to \user_id\ASSETS\Cash at bank\stock\Cash in Hand, which does not exist (Cash at bank node does not exist under ASSETS).
You are then attaching a ChildEventListener to this reference, which won't return any values, because there aren't any children under it (as it doesn't exist).
Inside onChildAdded(), you are trying to access the houses node which also doesn't exist in your example (house does though).
To access the children under the Stock node, you'll need something like:
ref = FirebaseDatabase.getInstance().getReference().child("user_id").child("ASSETS").child("Stock");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.child("house").child("values").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: "+value);
}
// ...
});
The DatabaseReference#child() method is not a SELECT statement. To access everything underneath a node, you only need to create a reference to the highest node required, then attach a listener to that.
For example, if you need access to everything underneath the ASSETS node, you could attach a listener there instead:
ref = FirebaseDatabase.getInstance().getReference().child("user_id").child("ASSETS");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("Stock").child("house").child("values").getValue(String.class);
Log.d(TAG, "onChildAdded: the value is: "+value);
if (dataSnapshot.child("Cash at bank").exists()) {
String value = dataSnapshot.child("Cash at bank").getValue(String.class);
Log.d(TAG, "onChildAdded: the cash at bank is: "+value);
}
}
// ...
});
Then when the listener returns you can use DataSnapshot#child() instead to access the individual values retrieved from that location. Also, using DataSnapshot#exists() is a simple way to check that a node exists before using it.
If you plan to have additional values or nodes under ASSETS that don't currently exist, they will be returned by the above listener as soon as they are created.
To achieve this, i suggest you using ValueEventListener like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference stockRef = rootRef.child("user_id").child("ASSETS").child("Stock");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String values = ds.child("house").child("values").getValue(String.class);
Log.d("TAG", values);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
stockRef.addListenerForSingleValueEvent(eventListener);