Okay so I got it to run showing the User ID but not score. I then began making some changes, forgot what I'd changed and now I'm back to null null again. I feel like I may have deleted something or misspelled something.
dbref.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
list.clear();
for(DataSnapshot ds :dataSnapshot.getChildren()) {
Score Result = ds.getValue(Score.class);
String userId = String.valueOf(Result.getUserId());
String score = String.valueOf(Result.getScore());
list.add(userId);
list.add(score);
}
adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, list);
LvRanking.setAdapter(adapter);
}
Here's my model:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
#Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Database:
Link to my database screenshot
This is a classic issue with asynchronous APIs. In order to make it work, change your model class according to Java Naming Conventions. Your class should look like this:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
#Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Also note that onDataChange() method has an asynchronous behavior, which means that is called even before you are trying to add those objects of Score class to the list. In other words, your list will always be empty outside that method. A quick fix would be to move the declaration of your list inside onDataChange() and do what you want to do with it or, if you want to dive into the asynchronous world and use my answer from this post.
Assuming the score node is a direct child of your Firebase root, to display the data using the String class, please use the following code:
ListView listView = (ListView) findViewById(R.id.list_view);
List<String> list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("userId").getValue(String.class);
String score = ds.child("score").getValue(String.class);
list.add(userId + " / " + score);
Log.d("TAG", userId + " / " + score);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
And this how you can display data using the Score class.
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Score score = ds.getValue(Score.class);
String userId = score.getUserId();
String score = score.getScore();
Log.d("TAG", userId + " / " + score);
list.add(score);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
filepath.addOnSuccessListener(upload data first) then get it and use it....
Related
I created tabbed activity for my project. I have three tabs which are Paid , Unpaid and Item Posted
I want to classify every of them based on the status. I have created the coding but I'm not sure on how to implement the method inside my coding. I want only order that have "PAID" as their status will be shown up inside my PaidFrag.
PaidFrag:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ds : orderSnapshot.getChildren()) {
Order order = ds.getValue(Order.class);
if (order.getStatus().equals("UNPAID")) ;
orderList.add(ds.getValue(Order.class));
}
}
psOrderAdapter PsOrderAdapter = new psOrderAdapter(orderList);
recyclerView.setAdapter(PsOrderAdapter);
}
}
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.name.setText("Name : " + orderList.get(i).getName());
myViewHolder.status.setText("Status : " + orderList.get(i).getStatus());
myViewHolder.total.setText("Total Price : RM " + orderList.get(i).getTotal());
myViewHolder.address.setText("Address : " + orderList.get(i).getAddress());
myViewHolder.dateTime.setText("Order ID :" + orderList.get(i).getOrder_id());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cust_id = orderList.get(i).getCust_id();
String oid = orderList.get(i).getOrder_id();
String status = orderList.get(i).getStatus();
String courier = orderList.get(i).getCourier();
String track = orderList.get(i).getTrackingNum();
String num = orderList.get(i).getPhone();
Intent intent = new Intent(context, updateStatus.class);
intent.putExtra("cust_id",cust_id);
intent.putExtra("order_id",oid);
intent.putExtra("status",status);
intent.putExtra("courier", courier);
intent.putExtra("trackingNum",track);
intent.putExtra("phone",num);
context.startActivity(intent);
}
});
It sounds like you're looking for a Firebase Database query, which limits what nodes are returns from the database:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
Query query = databaseReference.orderByChild("status").equalTo("PAID");
query.addValueEventListener(new ValueEventListener() {
...
You'll need to make sure that the status and PAID strings match the exact key and value that you have in your database.
For more on this, see the Firebase documentation on ordering and filtering data.
Does if else statement get executed in adapter class?
I'm trying to make a notification message like Shopee apps. So I want user to receive notification if the admin have submitted the customer tracking number, the customer will received message in the notification page that will displayed the text including their tracking number. If they don't have the tracking number yet. The notification will not supposed to be displayed on the customer page.
the yellow highlighted is the correct output but the red line is not. That notification was not supposed to come out yet because the admin has not been updated the customer order tracking number.
my apps
this is my database
adapter class
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
if (orderList.get(i).getTrackingNum() == ""){
myViewHolder.note.setText("Your order has not been shipped yet!" +orderList.get(i).dateTime);
}
else
myViewHolder.note.setText(" Your order ID :" + orderList.get(i).getDateTime()+" has been posted. The Tracking number is :" + orderList.get(i).getTrackingNum());
}
notificationClass
protected void onStart() {
super.onStart();
if (dbNotification != null) {
dbNotification.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapShot : dataSnapshot.getChildren()) {
for (DataSnapshot ds : orderSnapShot.getChildren()) {
orderList.add(ds.getValue(Order.class));
}
}
}
notificationAdapter NotificationAdapter = new notificationAdapter(orderList);
recyclerView.setAdapter(NotificationAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CustNotification.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
public class Order {
public String cust_id;
public String cart_id;
public String total;
public String name;
public String address;
public String phone;
public String status;
public String dateTime;
public String courier;
public String trackingNum;
public String methodPay;
public Order() {
}
public Order(String cust_id, String cart_id, String total, String name, String address, String phone, String status, String dateTime,String courier, String trackingNum, String methodPay) {
this.cust_id = cust_id;
this.total = total;
this.name = name;
this.address = address;
this.phone = phone;
this.cart_id = cart_id;
this.status = status;
this.dateTime=dateTime;
this.courier=courier;
this.trackingNum=trackingNum;
this.methodPay=methodPay;
}
To answer your question explicitly -- Yes, you can use logic such as if-else inside your onBindViewHolder() method.
As for why your logic may not be working, maybe you should change your if statement to use TextUtils.isEmpty and see if that works.
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
if (TextUtils.isEmpty(orderList.get(i).getTrackingNum())) {
myViewHolder.note.setText("Your order has not been shipped yet!" + orderList.get(i).dateTime);
} else {
myViewHolder.note.setText(" Your order ID :" + orderList.get(i).getDateTime() + " has been posted. The Tracking number is :" + orderList.get(i).getTrackingNum());
}
}
I've try for hours to read the 0 and 1 in products branch. Please someone well-experienced in firebase database help me :(
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Food uInfo = new Food();
uInfo.setName(ds.child("products").getValue(Food.class).getName());
uInfo.setIngredients(ds.child("products").getValue(Food.class).getIngredients());
//display all the information
Log.d(TAG, "showData: name: " + uInfo.getName());
Log.d(TAG, "showData: ingredients: " + uInfo.getIngredients());
ArrayList<String> array = new ArrayList<>();
array.add(uInfo.getName());
array.add(uInfo.getIngredients());
[ArrayAdapter adapter = new][1] ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
}
You're doing it wrong.
First, make sure your model class Food contains all the fields you wanna parse.
public class Food
{
private String NDB_number;
private String long_name;
private String ingredients_english;
public String getNDB_number() {
return NDB_number;
}
public void setNDB_number(String NDB_number) {
this.NDB_number = NDB_number;
}
public String getLong_name() {
return long_name;
}
public void setLong_name(String long_name) {
this.long_name = long_name;
}
public String getIngredients_english() {
return ingredients_english;
}
public void setIngredients_english(String ingredients_english) {
this.ingredients_english = ingredients_english;
}
public Food(String NDB_number, String long_name, String ingredients_english)
{
this.long_name = long_name;
this.NDB_number = NDB_number;
this.ingredients_english = ingredients_english;
}
}
then you can parse the products as follows
// Get a reference to our Products
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("foodnutrientstest").child("Products");
// Attach a listener to read the products
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Food food = ds.getValue(Food.class);
//display all the information
Log.d(TAG, "showData: name: " + food.getLong_name());
Log.d(TAG, "showData: ingredients: " + food.getIngredients_english());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Cheers :)
To get that data, simply uste the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String NDB_number = ds.child("NDB_number").getValue(String.class);
String ingredients_english = ds.child("ingredients_english").getValue(String.class);
String long_name = ds.child("long_name").getValue(String.class);
Log.d(TAG, NDB_number + " / " + ingredients_english + " / " + long_name);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
productsRef.addListenerForSingleValueEvent(valueEventListener);
I have used the String class to get your data because your fields are not correctly named and the object from the database will to be able to be mapped into a Food object. Having that data, you can now create a new object of your Food class and use in the way I need.
A more appropriate names for your fields would be:
private String ndbNumber;
private String ingredientsEnglish;
private String longName;
Kotlin solution:
class products {
lateinit var productsDataModel: Products_data_model
lateinit var productList:ArrayList<Products_data_model>
val firebasereference=FirebaseDatabase.getInstance().reference.child("foodnutrientstest").child("products")
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
for(data in p0.children)
{
val ndb=p0.child("NDB_Number").getValue().toString()
val ingredient=p0.child("ingreidents_english").getValue().toString()
val long_name=p0.child("long_name").getValue().toString()
productsDataModel=Products_data_model(ndb,ingredient,long_name)
productList.add(productsDataModel)
}
display(productList)
}
})
private fun display(productList: java.util.ArrayList<Products_data_model>) //here you can get all data
{
for(i in 0 until productList.size)
{
Log.d("ndb_name",productList[i].name)
Log.d("ingredient name",productList[i].ingredient)
Log.d("long name",productList[i].long_name)
}
}
}
product_data_model.kt
class Products_data_model {
var name:String
var ingredient:String
var long_name:String
constructor(name:String,ingredient:String,long_name:String)
{
this.name=name
this.ingredient=ingredient
this.long_name=long_name
}
}
I want to get all data from firebase and also want to store that data to firebase recyclerview. The code is showing only last entry into recycler view. but when i delete last data from firebase it will showing second last data. OR How do i add child field to firebase recyclerview.
mDatabase.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
keys = datas.getKey();
date = datas.child("date").getValue().toString();
IsCompleted = datas.child("isCompleted").getValue().toString();
MobileNoFB = datas.child("mobileNo").getValue().toString();
//Toast.makeText(YourOrdered.this, "Date is :- " + date + " IsCompleted:- " + IsCompleted, Toast.LENGTH_LONG).show();
if (MobileNoFB.matches(MobileNumber)) {
moDatabase = FirebaseDatabase.getInstance().getReference().child("Pending_Orders").child(keys).child("Orders");
// Recyclerview data
final FirebaseRecyclerAdapter<YourOrderAdapter, YourOrderViewHolder> YORecyclerView = new FirebaseRecyclerAdapter<YourOrderAdapter, YourOrderViewHolder>
(YourOrderAdapter.class, R.layout.client_order, YourOrderViewHolder.class, moDatabase) {
#Override
protected void populateViewHolder(final YourOrderViewHolder viewHolder, final YourOrderAdapter model, final int position) {
viewHolder.setProImage(getApplicationContext(), model.getProductImage());
viewHolder.setProductQuantity(model.getProductQuantity());
viewHolder.setDate(date);
viewHolder.setIsCompleted(IsCompleted);
viewHolder.setProductColor(model.getProductColor());
viewHolder.setProductNo(model.getProductNo());
}
};
YORecyclerView.notifyDataSetChanged();
mBlogList.setAdapter(YORecyclerView);
} else {
Toast.makeText(YourOrdered.this, "Ordered does not found...", Toast.LENGTH_LONG).show();
}
//Toast.makeText(YourOrdered.this, "I is:- " + i, Toast.LENGTH_LONG).show();
}
//Toast.makeText(YourOrdered.this, "Date is :- " + date + " IsCompleted:- " + IsCompleted,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please remove
`mBlogList.setAdapter(YORecyclerView);`
from for loop and add it after for loop
`mBlogList.setAdapter(YORecyclerView);`
I want to get a string from this:
, but it has a unique key parent. How do I get string from db? I tried:
firebaseAuth = FirebaseAuth.getInstance();
fUID =firebaseAuth.getCurrentUser().getUid();
itemsUrl ="https://nextweaverproject.firebaseio.com/users/" + fUID ;
mDatabase = FirebaseDatabase.getInstance();
final DatabaseReference myRef = mDatabase.getReferenceFromUrl(itemsUrl);
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = new ArrayList<Object>(td.values());
strFb = new ArrayList<String>();
strFb.add(values.get(0).toString());
// strFb.add(urlLong);
Log.v("test"," " + strFb.get(strFb.size()-1));
}
But It returns all objects in db.
You can use child to get data from the database tree:
myRef.child("Scenes").child("Scene").("******").
(*****).addChildEventListener(new ChildEventListener() {
this way you should chain your fields.
You can use also addValueEventListener, addListenerForSingleValueEvent.
You can read about them here:
https://firebase.google.com/docs/database/android/retrieve-data
Thank you all. I found my solution by this:
myRef.child("Scenes").child("Scene").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot children : dataSnapshot.getChildren()) {
for (DataSnapshot child : children.getChildren()) {
//Log.v("key1"," " + child.getKey());
if(child.getKey().equals("Thumb")){
for (DataSnapshot child2 : child.getChildren()) {
//Log.v("key2"," " + child2.getValue(String.class));
for (DataSnapshot child3 : child2.getChildren()) {
//Log.v("key3"," " + child3.getKey());
if(child3.getKey().equals("LongUrl")){
Log.v("key4"," " + child3.getValue(String.class));
thumbUrl.add(child3.getValue().toString());
}
}
}
}
}
Log.v("keyResult"," " + thumbUrl);
// Log.v("key2"," " + thumbUrl);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Result here :Result