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.
Related
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'm developing an Android app in Android Studio which lists events based on categories (music, sport, business, theatre). Every event has a name, description, location and time. This is how the events are stored in Firebase when a user posts events through my application:
How can I retrieve e.g. all childs and its contents in the Music category? I have four String arrays to display events (currently manually) like this:
String[] name = {"Eminem","Rihanna"};
String[] desc = {"Concert","Live Show"};
String[] location = {"Miami","Florida"};
String[] time = {"bllablla","bllablla"};
I want to populate the string arrays automatically from firebase, however I'm not sure how to get contents for every child element from Music element? If needed, I can post the Java code which populates the database as well.
Edit: I've tried this:
DatabaseReference info = FirebaseDatabase.getInstance().getReference("Events").child("Music");
info.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot val: dataSnapshot.getChildren()) {
// Retreive all Music childs and then retreive all data of them childs?
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
There is probably no easier solution than to download all of your music data, loop through all children and create corresponding arrays manually -
1) Create a class to map your firebase music record to -
class MusicRecord{
String date;
String eventDescription;
String eventName;
String location;
}
2) Load data, loop through children, retrieve MusicRecords and populate your arrays
protected void loadData(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Events").child("Music");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> recordsSnaphots = dataSnapshot.getChildren();
int count = (int) dataSnapshot.getChildrenCount();
int i = 0;
String[] names = new String[count];
String[] descriptions = new String[count];
String[] locations = new String[count];
String[] times = new String[count];
for(DataSnapshot recordSnapshot: recordsSnaphots){
MusicRecord record = recordSnapshot.getValue(MusicRecord.class);
if(record != null) {
names[i] = record.eventName;
descriptions[i] = record.eventDescription;
locations[i] = record.location;
times[i] = record.date;
i++;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Based on your post, you'll have to do several things :
Create a model
You'll have to create a POJO that describes the structure of the data you have in your Firebase realtime database. In your case, create a class FirebaseEvent that has a Date and three Strings (eventDescription,eventName,location).
Instantiate your class
Based on your last snippet, instantiate your class with the data from your Firebase realtime database. Firebase API is still a bit tedious with this, but this is yet the most common way to do it
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<HashMap<String,FirebaseEvent>> ti =
new GenericTypeIndicator<HashMap<String,FirebaseEvent>>() {};
HashMap<String,FirebaseEvent> retrievedEvents = childSnapshot.getValue(ti);
}
Now, what you have is a HashMap with keys like "Eminem" and "Rihanna" and the corresponding value that is a FirebaseEvent.
I choose to use an ArrayList for a dynamic data structure.
I also took a snapshot of my database:
public class MainActivity extends AppCompatActivity {
List<String> name= new ArrayList<String>();
List<String> location= new ArrayList<String>();
List<String> date= new ArrayList<String>();
private DatabaseReference mDatabase;
public static final String TAG= "YOUR-TAG-NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Events").child("Music");
// Read from the database
mDatabase.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.
for (DataSnapshot values: dataSnapshot.getChildren()) {
//query for the parent of the date "Eminem"
String key = values.getKey().toString();
name.add(key);
//query for location in the music category
date.add(values.child("location").getValue().toString());
//query for date in the music category
date.add(values.child("date").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}
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....
I am new in Firebase and that's my first App using Firebase.
My App got 15 different Scores and I separate them with a Spinner. Each time a different score is selected, it shoult be re-sorted.
It works, it always shows the correct scores but not Ordered.
Database:
My Code:
FirebaseDatabase database;
DatabaseReference databaseReference;
Query myQuery;
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference().getRef().child("Users");
for (int i = 0; i < spinner.getCount(); i++) {
int x = i+1;
if (i == spinner.getSelectedItemPosition()) {
prefsEdit.putInt("selectedScore", x).apply();
myQuery = databaseReference.orderByChild("score"+possibleScores.get(i));
downloadScores();
break;
}
}
public void downloadScores() {
myQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
users.clear();
for (DataSnapshot post : dataSnapshot.getChildren()) {
Users user = post.getValue(Users.class);
users.add(user);
}
UsersList scoreAdapter = new UsersList(HighscoreActivity.this, users);
scoreList.setAdapter(scoreAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
And that's my result. For example Score 6
I tried to use this too
myQuery = databaseReference.child(firebaseAuth.getUid()).child("highscores").orderByChild("score"+possibleScores.get(i));
and got this error:
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.user.app.Users
So what I overlook?
Thanks a lot
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