How to retrieve data from a child node in Android Firebase - android

I already have a onDataChange written to get values from a different child node,but what I need is to change the key to let's say "new" and then retrieve the data from that child
Any inputs would be appreciated ..

As far as i understand, you want to change a field and bring back the changed data.
for e.g, for this data structure, if you want the change Username, create a User modal with different name, User newUser = new User("https://...","newUserName). And change the field in User modal
public String Profile;
public String newKey;
Then give the new modal to that uid,
FirebaseDatabase.getInstance().getReference().child("Users").child("ECWHIksxJ0Q5SUIIrev4BjnjmrJ3").setValue(newUser, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
DatabaseReference yourRef = databaseReference.getRef();
}
});
Now you have the changed data's reference. Did you try something like this?
Update:
If you want to update multiple value/field with single action, you should create a map and put every path into it with values.
In firebase, every table, every specific field is an path. Consider the data structure shown above. If you want change Username field:
HashMap<String, Object> updateMap = new HashMap<>();
updateMap.put("/Users/ECWHIksxJ0Q5SUIIrev4BjnjmrJ3/Username", "newUserName");
For different user:
updateMap.put("/Users/DIFFERENT_USER_KEY/Username", "newUserName2");
For diffrent table:
updateMap.put("/YourOtherTable/DifferentPath/DifferentField", true);
Then get your database root reference and update all at once.
FirebaseDatabase.getInstance().getReference().updateChildren(updateMap).addOnCompleteListener(new OnCompleteListener...)
This is very simple way to update a lot of things in one action, but it's causing problems when writing firebase rules. Because you get your root reference and try to set a value to it. The choice is yours.

Related

how to get all the values whose node names starts with kpk with only one string output

How can i get the values whose nodes starts with KPK or PU, as i only know the provinces/state names.
or how can i get only "node names" which starts with KPK.
or is there any structure which i can follow to get cities names starts with KPK/PU.
I just want to save city names and I only know province/state names.I want the modal class having only one string variable as cities will be added in future.So want to have a generic modal class.
With your current data structure you have two options:
Read all data under the root of what you've shown and filter client-side.
Perform two reads: one for every node that starts with kpk_ and one for every node that starts with pu_. And then merge them on the client.
The first approach is simpler, but reads too much data. The second approach only read the data that is needed, but the code will be more complex.
There actually is a third approach that will work with your current structure, but may stop working of you add more data. You can start at kpk_ and end at pu_~. This range includes exactly the nodes you want in the current JSON.
The code will be something like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/path/to/data");
ref.orderByKey().startAt("kpk_").endAt("pu_~").addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot child: snapshot.getChildren()) {
System.out.println(child.getKey()+": "+child.getValue(String.class));
}
}
public void onCancelled(DatabaseError error) {
throw error.toException();
}
});
Note that in general it is recommended to keep only data of a single type under a node. If you have a use-case where you need the pu_* and kpk_*, then consider adding an additional node in your JSON where you keep only those values. While it is more complex to write this additional structure, it will be more efficient and simpler to read.

Firebase real-time data base, add new timestamp child node upon every login?

I'm very new to firebase as this is my first project so any help is appreciated because this problem has taken quite a few hours of my time. I think the solution could be very simple but I'm failing to see it.
I would like to collect user-specific data upon every login to the app so it'd be something like this (in the real-time database):
-user-id{
-10:40:50:{
-location:"loation1",
-activity:"walking",
-batteryLevel:"90%"
}
-11:50:30:{
-location:"location2",
-activity:"running",
-battery-level:"80%"
}
}
I have tried to start by simply making different nodes (the timestamps) for every login before I go into more details with the children of these timestamps (location, activity and battery level).
I thought the code below would create something like this:
-user-id{
-10:40:50:"10:40:50"
-11:50:30:"11:50:30"
}
But instead I only get
-user-id{
-11:50:30:"11:50:30"
}
My problem is that every time the user logs in, the new timestamp overwrites the old one so user-id always has only one child node (the timestamp associated with the latest login).
This is the code I tried. PS: I have tried replacing ".setValue()" with ".push().setValue()" but the last timestamp always erases the previous one.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(firebaseAuth.getCurrentUser().getUid());
myRef.setValue( firebaseAuth.getCurrentUser().getUid());
String currentDateTime = DateFormat.getDateTimeInstance().format(new Date());
DatabaseReference usersRef = myRef.child(currentDateTime );
usersRef.setValue(currentDateTime);
The code above I've put it in the Oncreate of the activity "ProfileActivity.java" which is basically the activity the user is redirected to after he is correctly authenticated.
Thank you for your help.
This is a very silly mistake.
DatabaseReference myRef = database.getReference(firebaseAuth.getCurrentUser().getUid());
myRef.setValue( firebaseAuth.getCurrentUser().getUid());
These two lines of code always completely clear your node and set the value to your Uid.
If the node looked like this before
user123
- name:"peter"
- 10:40:50:"10:40:50"
it will now look like this
user123:"user123"
You set the complete content of the node to your Uid. If you just remove your myRef.setValue(...) statement, your problem will be solved.

Android studio firebase submission form

I'm new to Android studio. I was able to create login and auth for my app using firebase.
I'm now trying to create a submission form for the user to create and log all the fields in firebase. I would also need the ability as admin to approve the submission request and notify user by push notification or email. The email is one of the fields in the submission form.
Looking for some guidance.
Thanks
Use Firebase Realtime Database + Firebase Functions.
You can see examples here.
You'll need to use FirebaseDatabase for that, go through this to set things up-
https://firebase.google.com/docs/database/android/start/
So first of all, add a EditText fields (simplest way) for each entry you want in your xml such as emails, password, etc.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"/>
</EditText>
Next, in your java file, convert these entries to strings.
Create a DatabaseReference (Make sure you have included firebase database library in you app level build.gradle file) and point to the location where you want to store the form entries.
Create a HashMap in which you store id and entry of each field. Directly upload this map instead of uploading each and every field separately.
Don't forget to check that the entries aren't empty.
Somewhat like this-
//global variables in class
private EditText email;
private DatabaseReference mdatabase;
//inside onCreate() method
mdatabase=FirebaseDatabase.getInstance().getReference().child("Wherever you want to store this data");
email = (EditText) findViewById(R.id.emailf);
String mymail = email.getText().toString();
if(!TextUtils.isEmpty(myname)&&!TextUtils.isEmpty(mymail)&&!TextUtils.isEmpty(mypass))
{
//create a map
HashMap< String,String> hm =
new HashMap< String,String>();
hm.put("email", mymail);
hm.put("password", mypass);
hm.put("name", myname);
mdatabase.setValue(hm).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
//do whatever you want, your details have been uploaded to your database- mdatabase
}
}
});
}
Push Notifications can be implemented using Firebase Cloud Messaging service and node.js
You'll also need to learn about Firebase Functions, very necessary.
Begin here-
https://firebase.google.com/docs/cloud-messaging/
and here-
https://www.youtube.com/watch?v=BsCBCudx58g
and then here-
https://www.youtube.com/watch?v=2MYgZQjX7N0&list=PLk7v1Z2rk4hjxP_CHAhjXQN3zrcEhluF_
I hope this answered your question!

Android Parse.com getting the id of a user

I'm working in an android app adding the following/follower system, I'm using the lines in the Parse.com, I have a user profile, and when I click on the follow button the app send the both users id (the current user and the other user) in a row. I'm using pointers targeting the _user class.
This is my current code :
Intent i = get intent();
String userId = i.getStringExtra("userid");
ParseObject follow = new ParseObject("Follow");
follow.put("from",ParseUser.getCurrentUser());
follow.put("to", userId);
follow.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
btn_follow.setImageDrawable(getResources().getDrawable(R.drawable.ic_following));
}
});
The btn_follow change the image. which means the following has been done. but my Follow class is empty.
I have changed my Follow table from :
...|from|to|
To :
...|from|to|
This worked well the both users id were saved, but I need pointers not string so I put from and to to pointers again and deleted the line
follow.put("to", userId);
This worked well also but it only saved the current user and not the user I'm trying to follow.
So my problem is with the ID of the user I want to follow.
In the guide they are saying
"ParseUser otheruser = ..."
(I don't no what to put in the 3 points to get the other user id)
You need to assign a ParseObject (or ParseUser) to create a pointer in database. For this you need to create ParseUser without data, just with id like this:
follow.put("to", ParseObject.createWithoutData("_User", userId));
Also, you should check the ParseException e in callback to see whats going on.

Cannot save a ParseUser that is not authenticated, updating an object with a relation with a ParseUser

I am workin in an Android Project using parse.com and I have a table Requirement which has a column called "user_assigned" which is a relation to ParseUser. This user is in charge to modify the requirement even if he didn't create the Requirement, but when this user try to update the requirement values, it returns "Cannot save a ParseUser that is not authenticated"
P.D. All the ACL in the requirement are public, write and read.
// setting write permission
ParseACL postACL = new ParseACL(ParseUser.getCurrentUser());
postACL.setPublicWriteAccess(true);
postACL.setPublicReadAccess(true);
requirement.setACL(postACL);
requirement.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
callback.onFinish((Exception) e, requirement);
}
I don't want to change the user assigned I want to change other fields but the way I get and change the relation from the table is
ParseRelation<ParseUser> relation = requirement.getRelation("user_assigned");
relation.add(requirement.getUserAssigned());
I found a solution,
What is happening: 3 tables, Project, User and Requirements where a Requirement has a pointer to the Project and the Project has another pointer to an User called projectOwner. The problem happen when another user different to the projectOwner read some values of the projectOwner associated with the Requirements. If the new user wants to save some changes in the Requirements parse return the error "Cannot save a ParseUser that is not authenticated".
To fix it, i only read the objectId of the projectOwner and after I got the rest of the attributes of the ParseUser calling
ParseUser.getQuery();
query.get(objectId)
In other words, in my class Project, i have a method to get the attributes. When I want to get the projectUser (pointer) i got it like this:
User uTemp = (User) this.getParseUser("owner");
if(uTemp != null){
// this.setOwner(uTemp.extractAttributes());
uTemp = uTemp.getObjectId();
uTemp = UserDAO.getUserByObjectId(uTemp.getObjectId());
this.setOwner(uTemp);
}
I could fixed thanks to this, I hope it can be helpful.

Categories

Resources