Preset object Id when pushing to Firebase - android

I'm using a SortedList to sort my items inside the RecyclerView.
So I need to compare them by some unique Id, and Firebase provides awesome generated keys for that.
To push new value to a database I need to run:
public void addAdvert(Advert advert, String userId) {
String id = reference.child(NODE_USERS)
.child(userId)
.child(NODE_ITEMS)
.push()
.getKey() //execute this to just get the id
advert.setId(id);
getCurrentItemNode().child(advert.getId()).setValue(advert);
}
now my Advert item in database is fully equiped with Id and node key.
But I' curious, can I just write something like
reference.child(NODE_USERS)
.child(userId)
.child(NODE_ITEMS).push().setValue(advert);
And achieve the same result: both key and ID are set in database.

If you want to store the key in the item, you'll either have to perform two write operations or first generate the key and then write it.
But why do you want to store the key in the item to begin with?
As a side note, this code:
String id = reference.child(NODE_USERS)
.child(userId)
.child(NODE_ITEMS)
.push()
.getKey()
Is exactly the same as this:
String id = reference.push().getKey()
Firebase's push IDs are client-side generated, statistically guaranteed to be unique values. They're not dependent on the path and there is no round-trip to the database needed to determine these values.
See this blog post for more information: The 2^120 Ways to Ensure Unique Identifiers.

Related

Not able to use getRef() of Firebase in android

I need to update the data in Firebase database. I have displayed the data in Recyclerview. I need to get the child reference of the position i click in Recyclerview. An not able to use getRef() there to get the reference.
You need to generate a unique key with
String unique = reference.push().getKey();
when saving data to firebase, then you can use that unique key to modify content of that node later.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Transactions").child(uniqueId)...
You can show your getRef(position) method in your question, maybe another solution can come from there.

For android firebase how to write the query for finding child by string matching of child of child's value?

Assume this script:
private static DatabaseReference;
mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");
Query firebaseSearchQuery = mUserDatabase.child("service").orderByChild("serviceName").startAt(searchText).endAt(searchText+"\uf8ff");
FirebaseRecyclerAdapter<Workers, WorkerViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Workers, WorkerViewHolder>(
Workers.class,
R.layout.search_result_layout,
WorkerViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(WorkerViewHolder viewHolder, Workers model, int position) {
viewHolder.setDetails(model.getName(), model.getEmail());
}
};
What will be the query for finding users email by searching child of child's value (hardware) ?
There is no way to achieve this using this database structure.
First of all between Users node and service node there is another node, named userId, which does not appear in any reference. Between the service node and the child serviceName there is another node, serviceId node, which is the unique key generated by the push() method. I also don't see where are you looping to get those childrens. But these are not the actual problems.
In such cases as yours, you need to use a tehnique named in Firebase, denormalization and for that I recomend you see this tutorial, Denormalization is normal with the Firebase Database, for a better understanding.
So in your case, you need to create another node that will host only the services, so you can simply create a query. Unfortunately, Firebase does not allow you to query after multiple fields, so this is your only choice.

Create a unique ID for my child key in Firebase

My users can create jobs. I want to add these jobs to my Firebase DB. I want the structure of the DB to look like this
- jobs
--uid
---name
---descritpion
---...
For the "uid", I'd like a random and unique string. Is it possible to generate it automatically somehow instead of generating a random number by myself?
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("jobs").push().getKey();
get the instance of firebase and get reference to child jobs then get the key. the key will be unique.

Google App Engine - Datastore - Get an entity, not by it's key

I'm building an Android app, and I'm using Google App Engine to store user's data. I want users to be able to connect from other devices to their account, but I could not figure how.
The users table (kind) has 4 properties: id, email, nickname and level:
I have read this:
https://cloud.google.com/appengine/docs/standard/java/datastore/creating-entities
It's written their that I can only get entities by their key, and it's a problem for me, because in a new device, I can only get the user's email, not the key and Id. I need to get the key and id by their email.
Is this possible?
If it's not, is their any other solution?
You just need to do a simple query. What language are you using in the GAE backend? For example, in Python, you would do something like:
def get_user_by_prop(prop, value):
this_user = User.query(getattr(User, prop) == value).get()
return this_user
Judging from the link in your question, I assume you are using Java? Here are the docs for a query: https://cloud.google.com/appengine/docs/standard/java/datastore/retrieving-query-results
where they use the example:
Query q =
new Query("User")
.setFilter(new FilterPredicate("nickname", FilterOperator.EQUAL, "billybob"));
PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();
What is stored at the id property? Does it have some meaningful value or just random unique number to be used as a unique identifier?
It seems like you can design your database differently so the email address would be your unique identifier. In that case, you will have a User table contains the following properties:
email (your unique identifier), nickname and level.
That way you will be able to use the following code snippet:
Key userEmail; //Get user's email
Entity user = datastore.get(userEmail);
Regardless of that, you are still able to access your entity without the need for the entity's key, by using a query. That way you won't be using the entity's key in order to get its instance but you would rather get the desired entity by using the given property value and finding the matching entity with that property value.
The query would look something like that:
String userEmail; //Get user's email
Filter propertyFilter =
new FilterPredicate("email", FilterOperator.EQUAL, userEmail);
Query q = new Query("User").setFilter(propertyFilter);
PreparedQuery pq = datastore.prepare(q);
try {
Entity user = pq.asSingleEntity()
//Same as Entity user = datastore.get(userEmail) mentioned above
} catch (TooManyResultsException e) {
// If more than one result is returned from the Query.
// Add code for dealing the exception here
}

Obtaining the Unique Push ID in Firebase

Scenario is : json object are uploaded from a rest api and to be accessed by an android app.
Isuue: at each upload, the object is stored under unique push id. This is variable and not known at receiver end. So complete path is not known.
In given part of code:
mRootRef = new Firebase("https://solvewa2y.firebaseio.com");
Firebase messagesRef=mRootRef.child(postId);
I need to replace postId with something so that I can get the object stored irrespective of the unique id OR a way to get the unique id each time
The answer is really simple. I struggled for a solution with eventlisteners until I found this answer here
//Create new reference calling push creates the unique key in firebase database but has no data yet
DatabaseReference mypostref = databaseRef.push();
//Use the new reference to add the data
mypostref.setValue(data);
//Call getKey on the ref - you must have 'key' in your data class
String mypostref.getKey());

Categories

Resources