I am trying to fetch data from Firebase database from multiple child in single function. I have two child nodes in Firebase Favorites and Users
I am using RecyclerView to show list of Favorites User but i want to fetch one value name "Online" from Users node.
I add addValueEventListener on Favorites and add addListenerForSingleValueEvent on Users within Favorites addValueEventListener, but my addListenerForSingleValueEvent give null value.
There is my code:
mFavouriteDBRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mList.clear();
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot snap: dataSnapshot.getChildren()){
final Favourites user = snap.getValue(Favourites.class);
final FavouritesList[] holdObj = null;
//if not current user, as we do not want to show ourselves then chat with ourselves lol
try {
if(mAuth.getCurrentUser().getUid().equals(user.getUserId())){
//Firebase Reading data
mUsersDBRef = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).child("online").onDisconnect().setValue(false);
String local =dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("online").getValue().toString();
if(local.equals("true")){
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "true","Link");
}else{
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "false","Link");
}
mList.add(holdObj[0]);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
populaterecyclerView();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here my populaterecyclerView(); Class
private void populaterecyclerView(){
adapter = new UserFavouritesMeHomeListAdapter(context,mList);
adapter.setClickListener(UserFavouritesMeListHomeFragment.this);
recyclerView.setAdapter(adapter);
}
Thanks
Link of Image:
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124042847_file_cover.jpg
Data want to fetch from while reading Favorite
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124044659_file_cover.jpg
Related
I saved some data under a node with the currently signed in user UID, along with the post timestamp.I successfully manage to retrieve all the data under this node, but I would only like to retrieve the data for the currently signed in user, I am trying to create something similar to how amazon stores an item in the cart and when the user clicks the cart it shows the items they have added there, not all the items for every user. Can someone assist me with this problem?
public void addItemToCart(){
SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm:ss ");
Date date = new Date(System.currentTimeMillis());
timeStamp = loggedInUserId + formatter.format(date);
userDictionary.put("itemPrice", selectedPrice);
userDictionary.put("productname",productNameText);
userDictionary.put("description", selectedStringProductDescrtipon);
userDictionary.put("uid",loggedInUserId);
userDictionary.put("productImage", selectedImage);
userDictionary.put("datee",date.toString());
userDictionary.put("name",loggedInUserName);
userDictionary.put("timestamp",timeStamp);
uploadPostRef.child("Cart").child(timeStamp).setValue(userDictionary).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.i("sucessfully added","sucesssfully added to cart..");
getLoggedInUserData();
}
});
numberInCartIv.setVisibility(View.VISIBLE);
public void downloadCartData(){
cartDb.child("Cart").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (data.exists()) {
Log.i("data",data.toString());
// cartModel = data.getValue(CartModel.class);
// cartModelArrayList.add(cartModel);
// LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
// cartRecyleView.setLayoutManager(horizontalLayoutManager);
// cartAdapter = new CartAdapter(cartModelArrayList, getContext());
// cartRecyleView.setAdapter(cartAdapter);
} else {
Log.i("error", "Error Loading JSON data..");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
String error = databaseError.getDetails();
Log.i("error", error);
}
});
}
First of all, you need to change your DB json to this one.
Cart
-userUid
-cartUid
-datee
-description
-andSoOn
That's mean, when you are storing the item into Cart. You need to include the userUid.
//Getting userUid
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
final String userUid = firebaseUser.getUid();
uploadPostRef.child("Cart").child(userUid).child(timeStamp).setValue(userDictionary).addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Void unused) {
Log.i("sucessfully added","sucesssfully added to cart..");
getLoggedInUserData();
}
});
}
To retrieve the Cart according to the user. You just call them like this.
public void downloadCartData(){
cartDb.child("Cart").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (data.exists()) {
Log.i("data",data.toString());
} else {
Log.i("error", "Error Loading JSON data..");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
String error = databaseError.getDetails();
Log.i("error", error);
}
});
}
I have a RecyclerView with CardViews which come from my Firebase Realtime Database for different activities, for example, daily meals. I have added a delete button to the CardView which I would like to implement a delete from UI and database function. I know how to do these both separately, but I am unsure how to update the database after deleting the CardView from the UI.
At the moment, it is deleting from UI but not database, so when I go back to the activity, the card reappears. Each meal has its own random ID, not sure if that makes a difference but thought it is important to note.
Adapter Delete Function:
foodHolder.deleteMeal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
meals.remove(position);
notifyDataSetChanged();
}
});
Meal Activity (Where adapter is set):
mealRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
int total = 0;
for (DataSnapshot mealSnapshot : task.getResult().getChildren()) {
String grams = mealSnapshot.child("grams").getValue(String.class);
if (grams == null) {
textViewFoodCounter.setText("0");
} else {
total += Integer.parseInt(grams);
textViewFoodCounter.setText(String.valueOf(total));
}
if (meals != null) {
noMealsImg.setVisibility(View.GONE);
noMealsText.setVisibility(View.GONE);
} else {
noMealsImg.setVisibility(View.VISIBLE);
noMealsText.setVisibility(View.VISIBLE);
}
progressBar.setMax(1000); // make dynamic
ObjectAnimator.ofInt(progressBar, "progress", Integer.parseInt(grams))
.setDuration(300)
.start();
Meal data = mealSnapshot.getValue(Meal.class);
meals.add(data);
}
foodAdapter = new FoodAdapter(meals);
foodRecyclerView.setAdapter(foodAdapter);
} else {
Log.d("TAG", task.getException().getMessage());
}
}
});
CardView:
Firebase Meal Hierarchy:
You can do something like this. If anything is updated in the firebase database you can load your new data using addValueEventListener and onDataChange.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance().reference;
DatabaseReference dmoRef = firebaseDatabase.getReference().child(serialId);
dmoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//get your updated data
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Error fetching data", Toast.LENGTH_LONG).show();
}
});
I create database using curentdate (1-25) as parent id and using room (08-00_11-00_karpet1-) as child id. inside this database are user information that order that room (child id) on that date (parent id).
Question 1
using this layout design, how do i disable button that have been ordered so that indicate that room no longer available.
(example. user order karpet 14-17 on 1-28, when user create order database will update database datajadwal based on date (parentid) >> room (childid) >> userinformation (email.name.phone.etc) )
Question 2
each date have 5 rooms. when specific date click, room button will disabled according to the data on datajadwal and on that date (parentid), if there are no room data (childid) that means that room are available.
my situation =
i don't know hot to get the childid
private void datajadwalupdate(){
databseJadwal = database.getReference("datajadwal").child(haritanggalOrder);
databseJadwal.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
final String rooms = dataSnapshot.getKey();
databseJadwal.child(haritanggalOrder).child(rooms).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
this is where I'm, but got error on a null object reference
If I understand your question correctly, you will need all data under datajadwal to disable the correct buttons. In that case you can use a listener like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("datajadwal");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
String date = dataSnapshot.getKey();
for (DataSnapshot bookingSnapshot: dateSnapshot.getChildren()) {
String booking = bookingSnapshot.getKey();
// TODO: parse the booking into the time slot and room name
String timeslot = ...
String room = ...
// TODO: find the button for the room name and time slot and disable it
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
You need to iterate throught the childs of the snapshot and check the data, if there is user data then disable it.
DatabaseReference ref = rootRef.child(id).child(date);
ref.addValueEventListener(...
onDataChange...{
for (Snapshot child: dataSnapshot.getChildren()) {
//set the names as you are doing it
boolean occupied = child.hasChild("email)
button.setEnabled(!occupied)
}
}
You should create a POJO representing your entity and get the value from the snapshot child with getValue(YourPOJO.class)
I am trying to build a simple friend list, where the user can create some friend groups and each friend group can have a lot of friends, inside the friend group the user can add new friends by contact(inserting the phone number on a editText) the user is added in the list(I use recycleViews), each time I insert a new user in a friendList group in firebase it is added inside the group with the specific name(name can't be repeated for groups) with the userID and the value = true for that user, this is a representation of my firebase:
image the 't' refers to true
what I need, is to display all the users for a specific group, as long as I safe just the id inside my group, I need to get the entire user from that id, but not just 1 user I need to get them all.
So I did this:
private void prepareFriendList() {
myRef.child(id).child("FriendLists").child(group).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
currentFriends.add(snapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef.child(id).child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for(String item: currentFriends){
if (snapshot.getKey().equals(item)) {
usersList.add(user);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter.notifyDataSetChanged();
}
I'm currently developing an android app where I'm using firebase as database but when in got the variable in the onDataChange method and I assign them to a global variables I got null variables but when I call those variables in the onDataChange method they are not null.
public class PositionateMarkerTask extends AsyncTask {
public ArrayList<Location> arrayList= new ArrayList<>();
public void connect() {
//setting connexion parameter
final Firebase ref = new Firebase("https://test.firebaseio.com/test");
Query query = ref.orderByChild("longitude");
//get the data from the DB
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//checking if the user exist
if(dataSnapshot.exists()){
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
//get each user which has the target username
Location location =userSnapshot.getValue(Location.class);
arrayList.add(location);
//if the password is true , the data will be storaged in the sharedPreferences file and a Home activity will be launched
}
}
else{
System.out.println("not found");
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("problem ");
}
});
}
#Override
protected Object doInBackground(Object[] params) {
connect();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
System.out.println("the firs long is"+arrayList.get(0).getLongitude());
}
}
Even I got the same problem. Just pass the arraylist values inside the onDataChange to another method.
myFirebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("FIREBASE",String.valueOf(dataSnapshot.getChildrenCount()));
if (dataSnapshot.exists()){
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.d("FIREBASE ","FOR LOOP");
//Arraylist codes
iosTitleVal.add(snapshot.getKey().toString());
iosDescVal.add(snapshot.getValue().toString());
Log.d("FIREBASE","ArrayList KEY IS "+iosTitleVal);
//Passing arraylist values to another method
storageContainer(iosTermTitle,iosTermDesc);
}
}else {
Log.d("FIREBASE","NO DATAS");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here's my storageContainer method. In this method I passed the arrraylist values to RecyclerView Adapter's constructor.
public void storageContainer(ArrayList<String> arrayListTitle, ArrayList<String> arrayListDesc){
iosTitleStorage = arrayListTitle;
iosDescStorage = arrayListDesc;
//No null exception here...
Log.d("FIREBASE"," My Data KEY "+iosTitleStorage +" and VAL "+iosDescStorage);
}
I hope it'll work