Realtime database get name and value - android

i am using firebase real-time database.
there is the user name like - user1 and then some supplies he requested like the supplies name - markers and then the quantity - like 5.
this is my JSON file
{
"Users" : {
"User1" : {
"Markers" : 5,
"Scissors" : 1,
"Staplers" : 4
},
"User2" : {
"Markers" : 2,
"Scissors" : 5,
"Staplers" : 3
}
}
}
i want to get back the supplies whan i ask for in the format of:
markers 5
scissors 1
Staplers 4
the information comes out via a listview but i don't know how to get via the listview both name and quantity, i can get only one of them.
The code i am using to get only the names is:
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
and the code i am using to get only the quantity is:
// two first lines are the same
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getValue().toString());
}

Try something like this instead:
for (DataSnapshot supply : dataSnapshot.getChildren()) {
String key = supply.getKey();
String value = supply.getValue();
}
Also, you could have just saved i.next() to a variable, then you can access the key and value within the same loop without calling additional i.next() (which I presume is what the question is about).

i have changed the script to this one
key = (((DataSnapshot) i.next()).getKey());
value = ((dataSnapshot).child(key).getValue().toString());
set.add(key+" "+value);
it works very good, thanks any way.

Related

Can't convert object of type java.lang.String to type com.thesis.joinerapp.Model.Joins

So i want to query my Firebase Database base on the value that i get from other activity.
private String tripID = "";
tripID = getActivity().getIntent().getStringExtra("tripID");
JoinRef = FirebaseDatabase.getInstance().getReference().child("Join").child(tripID);
FirebaseRecyclerOptions<Joins> options = new FirebaseRecyclerOptions.Builder<Joins>().setQuery(JoinRef,Joins.class).build();
Database Structure:
But it shows an exception
com.google.firebase.database.DatabaseException: Can't convert object
of type java.lang.String to type com.thesis.joinerapp.Model.Joins
While FirebaseUI can perform look ups of data for you, your data has to be in a very specific format for that.
If you want to show a subset of the number of trips, the index has to look like this:
"myTrips": {
"tripID1": true,
"tripID2": true
}
Where tripID1 and tripID2 are the -L keys that you have under /Trip.
You can find another example of this data in the FirebaseUI documentation on showing indexed data.
when you want to use the FirebaseUi, your database structure should be like this.
{
"Join" : {
"tripID" : {
"pushUid" : {
"joinID" : "yourJoinID",
"personCount" : "1",
"tripID" : "yourTrioID",
"uid" : "yourUid"
}
}
}
}
You need to add new root child which is pushId.

Why am I getting the value from another key

Here is my data structure. I only want to get the "regular" key from the first key which is the -LZHfDw9kqC-3rBf4VRh
Here is my code:
String rates = null;
DataSnapshot ratesSnapshot = dataSnapshot.child(key).child("promos");
Adapter_RoomsModel roomsModel = new Adapter_RoomsModel();
for (DataSnapshot ds : ratesSnapshot.getChildren()) {
rates = ds.getKey();
roomsModel.setRateName(rates);
}
My output :
-LZHfDw9kqC-3rBf4VRh
regular
-LZQu0HReRqMhbnWgFJg
regular
This is working as expected. If you want only a single child value, your query will have to give the entire path to that location. For example, you will need to call out promos/-LZHfDw9kqC-3rBf4VRh/regular. You can't use wildcards.
If you don't know the name of a node, perhaps because it's a random push ID, then you need to query those children for the one(s) you want.

How to paginate in Firebase Database #AskFirebase

I am creating an application that is some kind of a personal vocabulary. The database is of the following form.
Now I need to implement a pagination, partial retrieval of the words of a user, but preserving the lexicographical order. Keeping words as keys (/user/{uid}/words/{word}) is not suitable, because handling homographs will be impossible in the future (as their key will coincide). I decided to keep additional property word for each user, so that I can call db.getReference().child("users").child(uid).child("words").orderByChild("word").
This will retrieve all words of a user. Now I need to paginate this query, e.g. first download 20 words and then again 20 etc., but preserving lexicographical order.
{
"users" : {
"yXYSqB016JMr1FIc85pvMbvqDDt2" : {
"words" : {
"5v1a1PaDKnTvvOH19kaFTa1iyOx2" : {
"index" : 1,
"word" : "apple"
},
"kXHakBKxk9TrAlWL1vTOCe0akk80" : {
"index" : 2,
"word" : "house"
},
"xSKSqB312JMrsFig15pvMbvqAAt0" : { ... }
}
},
"zCAtMpl9uxSjG9dJarGktTTs20w2" : { ... }
},
"vocabulary" : {
"en" : {
"5v1a1PaDKnTvvOH19kaFTa1iyOx2" : {
"definitions" : {
"a fruit that grows on a tree" : true
},
"word" : "apple"
},
"kXHakBKxk9TrAlWL1vTOCe0akk80" : { ... },
"xSKSqB312JMrsFig15pvMbvqAAt0" : { ... }
}
}
}
You seem to come from a SQL way of thinking, where you paginate by specifying the number of items to get and the number of items to skip. This is index-based pagination.
Firebase on the other uses cursor-based pagination. You tell it the nimber of items to get and at which item to start (or end). You identify this item by the value of the property on which you order, in your case that is the value of word. Since the same value could potentially appear in multiple children, you can also specify the key (the thing starting with 5v1a1...) of the child at which to start/end as a second parameter.
So say that you have a page size of two. You get the first 2 words with:
DatabaseReference allWords = db.getReference().child("users").child(uid).child("words");
Query firstPage = allWords.orderByChild("word").limitToFirst(2);
When you attach a listener to this, you'll get the first two words. You'll need to remember the word and the key of the last word in this first page:
String lastWordOnPreviousPage = "house";
String lastKeyOnPreviousPage = "5v1a1...";
Now if you need the second page of two words, you get them by:
Query secondPage = allWords.orderByChild("word").startAt(lastWordOnPreviousPage, lastKeyOnPreviousPage).limitToFirst(2);

How to access Firebase Database node using contains() method?

I am working on an app using Firebase Database. In my Firebase Database I have a node like xxxxxx_yyyyyy, where xxxxxx represents first user ID and yyyyyy represents second user ID. Now I want to retrieve only nodes which contains xxxxxx_ from my database. I don't know how to do this. Because all I know is Firebase gives only equalsTo() method.
There is no query like contain(). I recommend to change node structure (locating yyyyy under xxxxx).
There Is no Query Like Contains in Fire base.!
if you dnt want to change structure of your node you can Store Data in list and then simply use list.contains() you will get your desired Result.!
HtBVbQP0qMSrCStroYsIiMSuhMC3 //node userID
Name:XXXXXXX
You can get this Data by using orderbychild(XXXXXX);
There is no contain() method, however, you can solve this problem in two ways:
Using the split() method from String class.
Using Regex Pattern
Here is the code:
String firebaseField = "xxxxxx_yyyyyy";
String[] data = firebaseField.split("_");
System.out.print("Using split method: ");
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Or
System.out.print("\nUsing Regex Pattern: ");
Pattern datePattern = Pattern.compile("_");
data = datePattern.split(firebaseField);
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Hope it helps.

How to add array value in Firebase

I want to add some certain data to a Firebase as arrays. Example:
groups : ['a','b','c']
How can I add and read data in Firebase from Android?
When you have a structure like that, you actually shouldn't be using an array to model it. It seems much more like a set in my eyes.
In the Firebase Database sets are best modeled as keys, since that automatically guarantees that items are unique. So your structure then becomes:
groups: {
"a": true,
"b": true,
"c": true
}
The true values are just markers, since Firebase won't allow you to store keys without a value.
Now to add a group to this, you'd use Firebase's setValue() function:
DatabaseReference root = FirebaseDatabase.getInstance().reference();
DatabaseReference groupsRef = root.child("groups");
groupsRef.child("d").setValue(true);
From the documentation:
setValue() - Record or change exists values
If you want to only append datas, you can to use updateChildren().
In Java, if we know that the data is array-like, it can be cast as a List:
Firebase julieRef = new Firebase("https://SampleChat.firebaseIO-demo.com/users/julie/");
julieRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
GenericTypeIndicator<List<String>> t = new GenericTypeIndicator?<List<String>>() {};
List messages = snapshot.getValue(t);
if( messages === null ) {
System.out.println('No messages');
}
else {
System.out.println("The first message is: " + messages.get(0) );
}
}
// onCancelled...
});
Check this best practices post from the Firebase Blog.

Categories

Resources