Getting name of child node which is holding another subchild - android

Child1
Child1.1
Subchild1
Subchild 2
Child 1.2
Subchild 1
Subchild 2
If I need to retrieve child1.1 and 1.2 how do I get them in textview?, as their subchild can be retrieved easily using datasnapshot.
I dont have enogh reputation to post image so have to type the structure of my firebase project. Hope my problem is understandable.
Code What i done is...
LoggedInRef.child(number).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot != null) {
if (sampleList != null) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
/* msg_List_Item msgLIST=ds.getValue(msg_List_Item.class);
msgList.add(msgLIST);*/
Log.d("MESSAGES<<<<<<<<", ds.getValue().toString() + "<<<<<<<<<<<<<<<<<<<<<<<<<<");
String msg = ds.getValue(String.class); // problem is here............................................
String time = ds.child("DateTime").getValue(String.class);
String tag = ds.child("Tag").getValue(String.class);
msg_List_Item msg_list_item = new msg_List_Item(msg, time, tag);
/* msg_list_item.setMsg(msg);
msg_list_item.setDateTime(time);
msg_list_item.setTag(tag);*/
msgList.add(msg_list_item);
MessageAdapter = new msgAdapter(msgList, getApplicationContext());
mRecyclerView.setAdapter(MessageAdapter);
sampleList.clear();
mRecyclerView.scrollToPosition(MessageAdapter.getItemCount());
}
}
}
else {
Toast.makeText(Message.this, "No data found", Toast.LENGTH_SHORT).show();
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}}
);

"1234567890" : {
"-L7AhB1GWZPNqlte0tiX" : {
"DateTime" : "09-03-2018 22:30",
"MSG" : "hiii ",
"Tag" : "ByMe"
},
"-L7AiOxVbSYAx8_0WqEa" : {
"DateTime" : "09-03-2018 22:35",
"MSG" : "how are you",
"Tag" : "ByMe"
},
"-L7Ak1lhqn9EfD5YCOou" : {
"DateTime" : "09-03-2018 22:42",
"MSG" : "what are u doing?",
"Tag" : "ByMe"
},
"-L7AkGekOzKzlLOwWNWp" : {
"DateTime" : "09-03-2018 22:43",
"MSG" : "I am fine",
"Tag" : "NotByMe"
here is my Re modified structure!!!. *Child node : * "DateTime", "MSG", "Tag" become easier to fetch by using push().

Related

Android Firebase Retrieving data as a list from multiple nods

I am using firebase realtime database in my first android app. I'm trying to retrieve data from firebase as an arraylist of "username" but i'm constantly having the Query returning a null result. i'm very new to firebase so i'm really struggling with data retrieval errors.
"Marchand" : {
"Taha" : {
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"
},
"Yasmine" : {
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"
}
.
.
.
This is one of my attempts, i tried to use the order-by-child method to iterate through the multiple nods that i have but i'm sure that it's not the right way to do this, this gives me null poiter exceptions because the datasnapshot is returning a NULL value :
referenceMarchand = rootNode.getReference("Marchand");
final ArrayList<String> types = new ArrayList<>();
Query users = referenceMarchand.orderByChild("username");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
types.add(dataSnapshot.child("username").toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
lets make use of some functions of firebase, Lets see it works for you.
part 1)
we will save it another way around
"Merchant" : {"Name" : "Taha"
"ID" :"-KSMCMCMnnkd"},//Firebase generated id
{"Name" : "Yasmine"
"ID" :"-KSMCMccccnkd"},//Firebase generated Id
...........
Part 2)
And Save the Details
"Details" : {
"ID" : "-KSMCMCMnnkd" //Firebase generated id
"adress" : "58 avenu St Eugène ",
"blockage" : false,
"latitude" : 35.7498635,
"longitude" : -0.5566705,
"mail" : "mailmail#gmail.com ",
"password" : "123456",
"signalement" : 0,
"telephone" : "0666666666",
"username" : "Taha"},
{
"ID":"-KSMCMccccnkd" //Firebase generated id
"adress" : "Address kkdndbdk ",
"blockage" : false,
"latitude" : 35.7498636,
"longitude" : -0.5566704,
"mail" : "randommail#gmail.com",
"password" : "bobo",
"signalement" : 0,
"telephone" : "06999999",
"username" : "Yasmine"}
In Part 1)
DatabaseRefrence ref = FirebaseDatabase.getInstance("/Path");
String id = ref.child("Merchant").push().getKey(); //Firebase generated id
Merchant merchant = new Merchant();
merchant.setId(id);
merchant.setName("SomeName");
ref.child("Merchant").child(id).setValue(merchant);
Part 2)
Detail detail = new Detail();
detail.setAddress("Some Address");
detail.setBlockage("false");
detail.setLatitude("SomeValue");
detail.setEmail("someText#gmail.com");
......
ref.child("Details").child(id).setValue(detail);
Now
List<Merchant> merchants = new ArrayList<>();
List<Detail> details = new ArrayList<>();
ref.child("Merchant").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Merchant merchant = snapshot.getValue(Merchant.class);
merchants.add(merchant);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
ref.child("Details").addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(Datasnapshot snapshot:dataSnapshot){
Detail detail = snapshot.getValue(Detail.class);
details.add(detail);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now you can get the details for some merchant or save it in local database for later querying.

Sorting dates in ascending order from firebase to recyclerView

i have a problem in sorting the dates in ascending order to display in recyclerview
Here below is my database structure in firebase-realtime-database
{
firstitem : {
"name" : "first_item_name",
"date" : "29/11/2018",
"user" : "random user",
"url" : "My Url",
"tag" : "firstitem"
},
seconditem : {
"name" : "second_item_name",
"date" : "20/11/2018"
"user" : "another user",
"url" : "a url",
"tag" : "seconditem"
},
thirditem : {
"name" : "third_item_name",
"date" : "20/11/2017"
"user" : "another user",
"url" : "a url",
"tag" : "thirditem"
}
etc....
}
By using the above structure i wants to display in ascending order according to dates, What query i should do to do this, Please a give me a solution to recover from this problem ,Thanks in advance.
Query MyEventsRef = FirebaseDatabase.getInstance().getReference().child("Workers Details").child(userID)
.child("My Events").orderByChild("From_Date");
//Display events
FirebaseRecyclerOptions<WorkerMyEvents> options =
new FirebaseRecyclerOptions.Builder<WorkerMyEvents>()
.setQuery(MyEventsRef, WorkerMyEvents.class)
.build();
FirebaseRecyclerAdapter<WorkerMyEvents, WorkerMyEventViewHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<WorkerMyEvents, WorkerMyEventViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final WorkerMyEventViewHolder eventsViewHolder, int i, #NonNull final WorkerMyEvents newEvents)
{
//Id with date and time key
final String IDs = getRef(i).getKey();
final String eventIDs = IDs.substring(0,18);
final String serve = list3.get(i);
NewEventsRef.child(eventIDs).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{

Unable to update value in Firebase database from Android app

With the following code, I have the "history node".
History Node
{
"History" : {
"-LJANnl9ofbXlxLGxTGg" : {
"destination" : "3 Paradise Row",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "1 Union St",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.25,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533494377
}
}
With the following code, I am trying to update "status" value to update from "accepted" to "arrived_loc". When I run the code, I have a yellow highlight in firebase but keeps the value of status "accepted".
update status to "arrived_loc"
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRefchild("History").orderByChild("driver").equalTo(driverId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot nodeDS = dataSnapshot.getChildren().iterator().next();
String key = nodeDS.getKey();
Log.e(TAG, "key = " + key);
String path = "/" + dataSnapshot.getKey() + "/" + key;
Log.e(TAG, "path = " + path);
HashMap<String, Object> update = new HashMap<>();
update.put("status", "arrived_loc");
rootRef.child(path).updateChildren(update);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
What am I doing wrong?
Edit #1
If I run this code:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.push().getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
I get an extra history node and no update:
"History" : {
"-LJAVN2iAWfRREdlBevb" : {
"destination" : "3 Union St",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "123 Main Street",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.38,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533496391
},
"-LJAVaFd3Gzq3iIZGHeP" : {
"payment response" : "approved",
"riderPaid" : "true",
"status" : "accepted"
}
}
Edit #2 - image of database frozen
Edit #3
I can't seem to get it working for some reason so I renamed "status" to be "requestStatus" and created a new variable called rideStatus like:
status = "arrived at pickup";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
rootRef.child(requestId).child("rideStatus").setValue(status);
This seems to work for now, but when I need to change the value of rideStatus, hopefully it will work.
Try with this code without push() function:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
(depends on what you need to achieve on your app, might be a little different)
Update #2:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
snapshot.getRef().child("status").setValue("arrived at pickup");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try with updateChildren():
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap<String, String> newData = new HashMap<>();
newData.put("status", "arrived_loc");
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History/" + driverId); // Or however the path is
rootRef.updateChildren(newData);

Get a specific child from Firebase

In my Firebase, I have a database for an app. Let's say this is my Firebase JSON:
{
"Users" :{
"User1":{
"City": "Genk"
}
,"User2":{
"City": "Hasselt"
}
,"User3":{
"City": "Genk"
}
,"User4":{
"City": "As"
}
,"User5":{
"City": "Genk"
}
}
}
Now what I want is an ArrayList with all the users with city Genk. How is this possible? I want to use this ArrayList to put the specific Users who live in the city Genk in a ListView.
I suggest you create another child from the root like "UsersCity", In that way you can just call this child and retrieve it to your listview. Here's what i did:
String key = mDatabase.child("post").push().getKey();
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng);
Map<String, Object> postValues = userPost.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/post/" + key,postValues);
childUpdates.put("/user-post/" + uid + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
Here's the Json output for that :
{
"post" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
},
"user-post" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
}
},
//This child node is for users where you'll want to get the $uid to use for creation of other child nodes.
"users" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"fullname" : "Test 1"
}
}
}
I am just a newbie programmer and I know my answer is not the best but I hope it could help you out with your problem. :)
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});

Retrieving child's Information from Firebase back to android studio

I am new to Android Studio and Firebase itself. I understand that in order to get the child's data from its unique ID, I might need to use a Data Snapshot method. For example, I need to retrieve the name from Firebase database back to android studio application. How do I implement it in this case? Help would be much appreciated!
{
"0Zs7aiWplRRJ5IJ5pazuUOxIdqz2" : {
"name" : "yeo",
"pos" : "intern",
"team" : "nwrs"
},
"kaLCjJFoGETWCWH42kNkc90b5Ku1" : {
"2016" : {
"9" : {
"25" : {
".priority" : 0.0,
"AM" : "",
"OT" : "",
"OVN" : "",
"PM" : "",
"TPT" : ""
}
},
"10" : {
"1" : {
".priority" : 0.0,
"AM" : "zxc11",
"OT" : "12",
"OVN" : "33",
"PM" : "222",
"TPT" : "54"
},
"26" : {
"AM" : "aa",
"OVN" : "gg",
"PM" : "ccc",
"TPT" : ""
},
"29" : {
".priority" : 0.0,
"AM" : "dd",
"OVN" : "aa",
"PM" : "ss",
"TPT" : "2fd"
}
}
},
"name" : "Jing Yang",
"pos" : "Intern",
"team" : "NWRS"
}
}
Below is my current code
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
set.add(((DataSnapshot)i.next()).getKey());
}
names.clear();
names.addAll(set);
arrayAdapter.notifyDataSetChanged();
I'll assume that root refers to the root of your database. In that case your onDataChange will get a snapshot of the entire data at that location. You can loop over them and get the properties of each child in turn with:
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
//set.add(childSnapshot.getKey());
set.add(childSnapshot.child("name").getValue(String.class));
}
names.clear();
names.addAll(set);
arrayAdapter.notifyDataSetChanged();
But I highly recommend that you create a Java class that represents the items in your list. In your case that can be as simple as:
public class Item {
public string name;
public string pos;
public string team;
}
Then you can read the items with:
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Item child = childSnapshot.getValue(Item.class);
set.add(item.name);
}
names.clear();
names.addAll(set);
arrayAdapter.notifyDataSetChanged();

Categories

Resources