Update field of a firebase key - android

I have a structure in the firebase with some keys, I would like to know how to update a field of the last key generated.
I need to retrieve the last key generated and update the data, how to do that ???
In Json format
What I would like to change "Status"
"-Kuxu1dX_aMcKZbqpGiQ" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h17",
"funcionario" : "João Cardoso",
"motivo" : "Carta",
"nome" : "Felipe Antunes",
"tempo" : -1506424666540,
"visita" : "null"
},
"-KuxuQuZzcTV5T-PHw18" : {
"Status" : {
"status" : "Engano"
},
"data" : "26/9/2017 às 8h19",
"funcionario" : "João Cardoso",
"motivo" : "Encomenda",
"nome" : "Felipe Antunes",
"tempo" : -1506424770025,
"visita" : "null"
}

To be able to make a change to an item, you'll first need to find that item with a query:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("7VCZ8oJSz...");
Query query = ref.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
childSnapshot.getRef().getChild("Status").setValue("New value");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "Query:onCancelled", databaseError.toException());
}
});

To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("7VCZ8oJSz...");
Query query = yourRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("Status").child("status").setValue("yourNewValue");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);

Related

Get score and Category for specific user from Firebase

i have the following json structure:
"Question_Score" : {
"anna_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "anna_01",
"score" : "20",
"user" : "anna"
},
"anna_03" : {
"categoryID" : "03",
"categoryName" : "Constitution",
"question_Score" : "anna_03",
"score" : "170",
"user" : "anna"
},
"stelios_01" : {
"categoryID" : "01",
"categoryName" : "Intelligence",
"question_Score" : "stelios_01",
"score" : "230",
"user" : "stelios"
},
"stelios_02" : {
"categoryID" : "02",
"categoryName" : "Widsom",
"question_Score" : "stelios_02",
"score" : "220",
"user" : "stelios"
},
I want for currentuser get the categoryID and score. So probably i need to check equality currentuser == user and then get the categoryID and score for this user. As i m new in firebase i find it a little difficult.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("Question_Score");
// Attach a listener to read the data at your profile reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Profile profile = dataSnapshot.getValue(Question_Score.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.v("The read failed: " + databaseError.getCode());
}
});
I dont know from here how to take the values of CategoryId and score to check equality. I ll apriciate any help!
If I understand you correctly you're trying to read the Question_Score child nodes that have a specific value for categoryID. You can do that with a Firebase Database query on the categoryID property:
database = FirebaseDatabase.getInstance();
questionScoreRef = database.getReference("Question_Score");
Query query = questionScoreRef.orderByChild("categoryID").equalTo("01");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Log.i(TAG, childSnapshot.getKey()+": "+childSnapshot.child("user").getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
questionScore.addValueEventListener(postListener);
This prints the key and user value of each child node that has categoryID of "01".

while retriving data from firebase, getters are returned null

I am trying to retrieve data from firebase. I have successfully established Firebase database but during retrieve operation the getter methods are returns a null value, how to retrieve that information?Object is not null but the getters are returning null.
public class ViewDatabase extends AppCompatActivity {
public FirebaseDatabase firebaseDatabase;
public DatabaseReference databaseReference;
public ListView listView;
public static final String TAG="ViewDatabase";
//Oncreate
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_database);
listView=findViewById(R.id.list);
firebaseDatabase =FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference();
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
//Retriving data
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> array = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User user = ds.getValue(User.class);
if (user != null) {
Log.i(TAG, "user is not null" );
} else {
Log.i(TAG, "user is null" );
}
if(user.getAddress()!=null){
Log.i(TAG, "address is not null" );
}
else{
Log.i(TAG, "address is null" );
}
array = new ArrayList<String>();
array.add(user.getAddress());
array.add(user.getDate());
array.add(user.getEmail());
array.add(user.getFname());
array.add(user.getGender());
array.add(user.getZone());
array.add(user.getLname());
array.add(user.getPhone());
}
ArrayAdapter adapter = new ArrayAdapter(this, layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
}
what am i doing wrong?
//JSON EXPORT
{"User" : {
"-LIN7aCLwUo7fdjSm5ij" : {
"address" : "jagraon",
"date" : "2018/7/27",
"email" : "gurjaps00#gmail.com",
"fname" : "Gurjap",
"id" : "-LIN7aCLwUo7fdjSm5ij",
"lname" : "Singh",
"phone" : "8727050501",
"zone" : "CARDIO ZONE"
},
"-LIN7iFVzA8eVShCSmwu" : {
"address" : "jagraon",
"date" : "2018/7/25",
"email" : "livtaran#gmail.com",
"fname" : "Gurlivtaran",
"id" : "-LIN7iFVzA8eVShCSmwu",
"lname" : "Singh",
"phone" : "8725000740",
"zone" : "STRENTH ZONE"
},
"-LIjA7Kox5dtN8jg9ywY" : {
"address" : "chuuu",
"date" : "Select Expiry Date",
"email" : "cbjj#tuj.dhhu",
"fname" : "dhhxc",
"lname" : "cvhh",
"phone" : "9856533565",
"zone" : "CARDIO ZONE"}
}
}
HERE'S the JSON export done from firebase.
You're reading from the wrong level in your database.
You're reading from the root, and then looping over the children directly under that. That means that you get a snapshot for /User and you're trying to read a User.class from that. That won't work, since there are no properties address, name, etc directly under /User. Those properties live one level lower in your JSON, so your code will need to loop over the individual users too.
One simple fix:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> array = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println(ds.getKey());
for (DataSnapshot userSnapshot : ds.getChildren()) {
System.out.println(userSnapshot.getKey());
User user = userSnapshot.getValue(User.class);
...
An alternative (and possibly better solution) might be to only read the /User node:
firebaseDatabase =FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference();
databaseReference.child("User").addValueEventListener(new ValueEventListener() {
...

How to get realtime database object filtered by param?

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("words");
Query word = ref.orderByChild("lang1").equalTo("home");
word.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Word w = singleSnapshot.getValue(Word.class);
Log.i(String.valueOf(R.string.app_name), new Gson().toJson(w));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.e(TAG, "onCancelled", databaseError.toException());
}
});
Could you tell me what am I doing wrong? Here I am, trying to get some "Words" from DB & send Json to Console...
UPD: Imported JSON file
{
"words" : {
"1" : {
"id" : 1,
"lang1" : "s1",
"lang2" : "d1",
"type" : "a"
} ,
"2" : {
"id" : 2,
"lang1" : "s2",
"lang2" : "d2",
"type" : "a"
} // ...
}
}

How to read / query data from one userID Firebase Android

I want to retrieve data for a given user ID, which I am storing as a value in the database under each user. My database structure looks like below:
user: {
UserID: {
uniqueId: {
Name: ""
Email: ""
userId: ""
}
UserID: {
uniqueId: {
Name: ""
Email: ""
userId: ""
}
}
I tried this but it doesn't seem to work as it doesn't display anything on the app:
FirebaseUser user = mAuth.getCurrentUser();
df.child("UsersTable").orderByChild("userid").equalTo(user.getUid())).addChildEventListener
even when I try to give a specific value like below, it still does not read from firebase:
------------- Updated:
I want to get all data from userID. so for example, I want to retrieve all information from fmXWU324VHdDb8v6h7gvNjRojnu33, which will be name, email and userid.
UserTable
{
"fmXWU324VHdDb8v6h7gvNjRojnu33" : {
"-KbJtw467nl6p253HZ537" : {
"Name" : "name1",
"Email" : "something1#something.com",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
}
},
"pJtC45fW0MMi352UiPWnWdIS7h88" : {
"-Kb012ls9iMnzEL723o9I" : {
"Name" : "name2",
"Email" : "something2#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0aq0q25FJq38256SrC" : {
"Name" : "name3",
"Email" : "something3#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0atopfK64F6jy124Qi1u" : {
"Name" : "name3",
"Email" : "something1#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
}
}
Update 2:
DatabaseReference df= FirebaseDatabase.getInstance()
.getReference("user").child(getCurrentUser().getUid());
df.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
get(dataSnapshot);
}
....
...
Update 3:
I assume based on what I am looking for (getting all data under defined userId) the query should look something like this:
df.child("UserTable").child(user.getUid())).addChildEventListener(new ChildEventListener()
However, this is throwing this error:
Can't convert object of type java.lang.String to type com.android.example.UserTable
Try Using addChildEventListener and Query like following..
mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//deal with data object
}
#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) {
}
});
OR use addValueEventListener
mReference.child("user").orderByChild("userId").equalTo(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//deal with data object
}
#Override
public void onCancelled(DatabaseError databaseError) {
//toastMsg(databaseError.getMessage());
Log.e(TAG, "onCancelled: " + databaseError.getMessage());
}
});
Use something like the below code which i am using in my application and it works -
public static void storagesSetup(final Context context){
if(!hasSignedInUser()) {
**your business logic here**
return;
}
// Write a message to the database
final DatabaseReference databaseRef = FirebaseDatabase.getInstance()
.getReference("cart").child(getCurrentUser().getUid());
// Read from the database
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
**put your business logic here**
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
A Firebase Database query inspects the child nodes directly under the location that you execute it on. If you want to order on a child property of those nodes (i.e. use orderByChild()), that property must exist at a fixed path under each child nodes.
In your case, you have two nested dynamic children, which means you:
can query a known user for their results ordered by score
can't query across all users for their results ordered by score
If you want to allow the latter query, you'll need to change your data model to allow it. For example, by keeping a list of all results across all players:
ResultsTable:{
"-KbJtw467nl6p253HZ537" : {
"Name" : "name1",
"Email" : "something1#something.com",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
},
"-Kb012ls9iMnzEL723o9I" : {
"Name" : "name2",
"Email" : "something2#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0aq0q25FJq38256SrC" : {
"Name" : "name3",
"Email" : "something3#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0atopfK64F6jy124Qi1u" : {
"Name" : "name3",
"Email" : "something1#something.com",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
}
}
Please get a idea from below code.
Order objects:
DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance()
.getReference();
DatabaseReference node = mDatabaseReference.child("order")
node.orderByChild("timestamp").equalTo("-KZFQLVAv_kARdfnNnib")
.addValueEventListener(mValueEventListener);
private ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.i(TAG, "onDataChange: " + snapshot.getValue());
// Your code
}
#Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "onCancelled: " + error.getMessage());
}
};
This return the first order object. Hope you get the point Thanks! :)

Get Uid from firebase

I am trying to find the uid from firebase. Let's say I have 3 users in my database, and I want to find the 3rd user uid.
Here is json formate witch is just export from firebase:
{
"-KVKrXu70Ziw0iRw46l5" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkVy5OojpsSUEI24" : {
"age" : 20,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrkzXy9duyiZq5bM0" : {
"age" : 21,
"emailId" : "ameerhamzaaaa",
"name" : "hamza"
},
"-KVKrl5Ax7ptodMYywzg" : {
"age" : 22,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKrr7E6b4-3x6tuwOX" : {
"age" : 23,
"emailId" : "ameerhamza",
"name" : "hamza"
},
"-KVKruES01regClm6tWW" : {
"age" : 24,
"emailId" : "ameerhamza",
"name" : "hamza"
}
}
Here is code what I done. But it is not working for me.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.child(newRef.getKey()).setValue(s);
final Query queryRef = myRef.orderByChild("emailId").equalTo("ameerhamzaaaa");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("Firebase UID ",dataSnapshot.getKey());//it always null
Student s = dataSnapshot.getValue(Student.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You're creating an extra child and you're searching within the parent. Try something like this:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference();
DatabaseReference newRef = myRef.push();
i++;
Student s = new Student("ameerhamza",i,"hamza");
newRef.setValue(s);
myRef
.orderByChild("emailId")
.equalTo("ameerhamzaaaa")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Student> data = dataSnapshot.getValue(new GenericTypeIndicator<Map<String, Student>>() {});
Map.Entry<String, Student> entry = data.entrySet().iterator().next();
String uid = entry.getKey();
Student s = entry.getValue();
Log.d("Firebase UID ", uid);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// handle error
}
});
It probably doesn't give you the exact id but should give you a better understanding of what's happening.
All Right fox after so much hard work, finaly i get my ANS , Here is how i get the UID from firebase, i use the Firebase Recyler Adapter to get Data From firebase and next you see your self what i done
adapter = new FirebaseRecyclerAdapter<Student, myViewHolader>(
Student.class,R.layout.item_row,myViewHolader.class,myRef
) {
#Override
protected void populateViewHolder(myViewHolader viewHolder, Student model, int position) {
Log.e("myFirebase UID",adapter.getRef(position).getKey());
}
};
recyclerView.setAdapter(adapter);

Categories

Resources