how i can get my info through the random key by push - java

I have JsonString by receive DataSnapShot:
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
in normal if i know the key (-L3Mh7kKl04GSrndbrVD) ill code:
JSONObject a = new JSONObject(c);
JSONObject jsonUser = a.getJSONObject("-L3Mh7kKl04GSrndbrVD");
But i dont have that key, How i can get that value (name, pass, img, ...) with code, im newbie. Thanks all alot

try this:
DatabaseReference references=FirebaseDatabase.getInstance().getReference().child("user");
references.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String name=data.child("name").getValue().toString();
String password=data.child("pass").getValue().toString();
String img=data.child("img").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here the reference is the user node, then using the for loop it will iterate inside every push id to give you the values (name,img,pass,...).

Try this
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String u_img = ds.child("u_img").getValue(String.class);
String u_pass = ds.child("u_pass").getValue(String.class);
String u_address = ds.child("u_address").getValue(String.class);
Log.d("TAG",u_img + " / " + u_pass + " / " + u_address);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Join Firebase Realtime Database with Java?

I am trying to join between two nodes with firebase in java, but I can't relate all the data and display it in the view correctly. Any solution?
This is the data in firebase:
Person
66db3d6a-c6cf-4577-a857-eca22cd55403
name:"aaa"
surname:"bbb"
mail:"john#hotmail.com"
id:"66db3d6a-c6cf-4577-a857-eca22cd55403"
User
4ad0c3db-a5b1-40bb-bfc1-35c15ec5af9c
nameUser:"john123"
password:"******"
idPerson:"66db3d6a-c6cf-4577-a857-eca22cd55403"
idUser:"4ad0c3db-a5b1-40bb-bfc1-35c15ec5af9c"
This is my code:
private void listAll(){
Map<String, String> valuesMapJoin = new HashMap<>();
databaseReference.child("Person").orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Map<String, String> valuesMapPerson =
(HashMap<String,String>)dataSnapshot1.getValue();
String idPerson = valuesMapPerson.get("id");
String name = valuesMapPersona.get("name");
String surname = valuesMapPersona.get("surname");
String surname = valuesMapPersona.get("mail");
databaseReference.child("User").orderByKey().equalTo(idPerson).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Map<String, String> valuesMapUser = (HashMap<String,
String>)dataSnapshot1.getValue();
String nameUser = valuesMapUsuario.get("nameUser");
String password = valuesMapUsuario.get("password");
listDataJoin.add(name + "-" + sourname + "-" + mail + "-" + nameUser + "-
" + password);
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, listDatosJoin);
listJoin.setAdapter(arrayAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void listAll(){
Map<String, String> valuesMapJoin = new HashMap<>();
databaseReference.child("Person").orderByKey().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
Map<String, String> valuesMapPerson =
(HashMap<String,String>)dataSnapshot1.getValue();
String idPerson = valuesMapPerson.get("id");
String name = valuesMapPersona.get("name");
String surname = valuesMapPersona.get("surname");
String surname = valuesMapPersona.get("mail");
databaseReference.child("User").orderByKey().equalTo(idPerson).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Map<String, String> valuesMapUser = (HashMap<String,
String>)dataSnapshot1.getValue();
String nameUser = valuesMapUsuario.get("nameUser");
String password = valuesMapUsuario.get("password");
listDataJoin.add(name + "-" + sourname + "-" + mail + "-" + nameUser + "-
" + password);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, listDatosJoin);
listJoin.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Use above code snippet main problem is you have adapter set inside for loop so your code not work perfectly

Firebase RealTime Database Delete First 20 item

DatabaseReference newReferance = database.getReference().child("Users");
Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
for (int i= 0; i < 5; i++){
//HOW ????
}
}
recyclerAdapter.notifyDataSetChanged();
}
}
Hi Dear guys. How do I select and delete the first 5 data in a real-time database? When the ArrayList reaches a certain limit, I want to delete the first 5 data from the database. I'd appreciate it if you could help with the problem.
How do I select and delete the first 5 data in a real-time database?
You can achieve this using Firebase Query's limitToFirst(int limit):
Create a query with limit and anchor it to the start of the window
And in code should look like this:
Query query = newReferance.orderByChild("timestamp").limitToFirst(5);
See I have used this limitToFirst() method that can help you find the first 5 items. To delete them, just attach a listener and inside the onDataChange() method use the following line of code:
dataSnapshot.getRef().removeValue();
final DatabaseReference newReferance = database.getReference().child("Users");
final Query query = newReferance.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
if (chatMessages.size() >= 10){
Query query1 = newReferance.limitToFirst(5);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
database.getReference().child("Users").setValue(null);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
recyclerAdapter.notifyDataSetChanged();
}
}
Although I'm set, it's all deleted. I can't erase the items I want. All cleared.
rootRef is the firebase database reference. whose instance we have to gained before trying to delete any value. you can see the code given below.
count = 0;
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
CommonLocationClass user = postSnapshot.getValue(CommonLocationClass.class);
if (count < 5) {
rootRef.child(user.getPhNo).removeValue();
count++;
}
}
}
}
#Override
public void onCancelled (DatabaseError firebaseError){
}
});
the CommonLocationClass is a getter setter model class i have made to make the fire-base implementation easy
you can try this it works for me
public void getDataFirebase() {
/*if (chatMessages.size() == MAX_MSJ_LIMIT){
database.getReference().child("Users").removeValue();
}*/
final DatabaseReference newRefere = database.getReference().child("Users");
Query query = newRefere.orderByChild("timestamp");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatMessages.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
HashMap<String, String> hashMap = (HashMap<String, String>) dataSnapshot1.getValue();
//String userMail = hashMap.get("useremail");
String userMessage = hashMap.get("usermessage");
String userCt = hashMap.get("usershow");
chatMessages.add(userCt + ": " + userMessage);
recyclerAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It didn't just erase the first 5 data.
if (chatMessages.size() >= 10) {
Query query1 = newRefere.orderByChild("timestamp").limitToFirst(5);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I solved the problem. With this code

Firebase - getValue in third child return null

I have a problem, when I want get value from firebase, getValue() return null
DataSnapshot appleSnapshot and DataSnapshot dataSnapshot - in console I see Key and Value correctly in Firebase too
Database Structure
Debugging
DataSnapshot setting - return Key but don't return Value (null)
String settingKey - return correctly String Key
String settingValue - return null
Why i cant get Value from my deeper childs?
private void readData(final ValidateJoinInterface validateJoinInterface, final String name, final String password, final String user) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
DataSnapshot setting = appleSnapshot.child(name).child("Settings").child("Password");
String settingKey = (String) appleSnapshot.child(name).child("Settings").child("Password").getKey();
String settingValue = (String) appleSnapshot.child(name).child("Settings").child("Password").getValue();
}
validateJoinInterface.validateJoin(correctName, correctPassword, correctUserId);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DTAG", "onCancelled", databaseError.toException());
}
});
}
Assuming that the name varaible holds a String value like in your example Aa and also assuming that Aa is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference settingsRef = rootRef.child(name).child("Settings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String password = dataSnapshot.child("Password").getValue(String.class);
Log.d("TAG", name + " / " + password);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
settingsRef.addListenerForSingleValueEvent(valueEventListener);
The output will be: Aa / Aaa.
You can getting any value like :
FirebaseDatabase.getInstance().getReference().child(name).child("Settings").child("Password")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG,"KEY - "+messageSnapshot.getKey() + "VALUE - "+messageSnapshot.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Crashlytics.logException(databaseError.toException());
sendMessageListener.onSendMessageFailure(databaseError.getMessage());
}
});

how to get count of child inside the parent child

database rules
my database
I have a problem with writing data in firebase database
It must give an id for the data using method postId()
Sometimes its give me a right id and another time wrong id or updata data in an id was created
the id must be like this for all user post
[user1]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
[user2]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
........................................................................
if (auth.getCurrentUser() != null) {
mDatabase.child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID).setValue(adver,
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(getContext(), "Data is saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Data isn,t saved , please try again", Toast.LENGTH_LONG).show();
}
}
});
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID);
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mAdUserDatabse.child("userid").setValue(auth.getCurrentUser().getUid());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void postId() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild(auth.getCurrentUser().getUid())) {
// run some code
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
please save my life
You're running a loop and overwriting value of postId again and again, so the postId is equal to the count of last child. So you're always getting the postId count for last user.
so have a look again at the part
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
Consider using separate key for every user's postId or make a function to get key for one user something like this
public void getPostId(String userId) {
final String postId = "post";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
long c = snapshot.getChildrenCount();
if(c==) postId = postId+"1";
else postId = postId+ c+1;
},
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};

How to sum up/aggregate values on Firebase

I have just added few values using Firebase:
Screen from Firebase
I would like to sum up those values and display 15 as a result in the log.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseReference beersRef = FirebaseDatabase.getInstance().getReference("Rank");
final ArrayList<Integer> score = new ArrayList<>();
score.add(9);
score.add(2);
score.add(4);
beersRef.push().setValue(score);
beersRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#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) {
}
});
To achieve this, please use the following code. It's the simples way.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rankRef = rootRef.child("Rank");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum =+ sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rankRef.addListenerForSingleValueEvent(eventListener);
Your output will be: 15
use ValueEventListner and , don't use childEventListner,
follow the below line...Here " UI and UI.class " means...java class name ..where you put getters and setters ...
here I store int value in firebase...so need to convert int value to String and set a text to text viewholder...if u don't store in int ..than u can use String
beersRef.addValueEventListener(new ValueEventListener() {`
#Override
public void onDataChange(DataSnapshot dataSnapshot) {``
int total = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UI result = ds.getValue(UI.class);
total = total + result.getMrp_final();
}
String tl = total + "";
tv_total.setText(tl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
make sure int total value is zero...
thankyou

Categories