I am building an app. I have a Firebase database with a bunch of products, each of them has a rating. I am displaying them in a ListView but want to sort them by their rating. Do I need to save them differently to get this to work ?
private ListView mTopRatedList;
ArrayList<String> mAllBeers = new ArrayList<>();
DatabaseReference Reference = FirebaseDatabase.getInstance().getReference().child("Beers");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_rated);
mTopRatedList =(ListView)findViewById(R.id.topRatedList);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mAllBeers);
mTopRatedList.setAdapter(arrayAdapter);
arrayAdapter.clear();
Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayAdapter.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
//arrayAdapter.add(snapshot.getValue().toString());
Beers beers = snapshot.getValue(Beers.class);
String beerClass = beers.getmName();
Float beerRating = beers.getmRating();
//Collections.sort()
arrayAdapter.add(beerClass+ "User Rating is " + beerRating);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
From the look of your code, each of your beers has a rating property in the database.
In that case you can show the beers ordered by rating by doing:
Reference.orderByChild("rating").addValueEventListener(new ValueEventListener() {
...
A few notes:
This will show the beers in ascending order of their rating, so with the lowest value first. If you want to show the highest rated beer first, Firebase does not have a built-in operator for descending sort. So you'll have to work around that by either reversing the results in your client-side code, or by including an inverted rating in the database too for this purpose. In the latter case you'd sort on the inverted rating, and then display the regular rating.
For this to work correctly it is important that the rating value is a number, and not stored as a string. When stored as a string it may work for values up to 9, but after that you'll run into cases where numerical ordering differs from the lexicographical ordering that Firebase will use for strings.
Please never leave onCancelled empty as it hides potential problems. Its minimal implementation is public void onCancelled(#NonNull DatabaseError databaseError) { throw databaseError.toException(); }.
Related
So, I am using android studio to make an app that displays data stored in firebase real-time database. The app is simple, it displays the name and phone number from firebase to the app.
The app works fine and even displays the data but the only thing is it displays the data/values with curly braces and an equal sign (like a JSON format) is there anyway I can make it display just the desired values and not the extra signs and punctuation
Code:
ArrayList<String> list =new ArrayList<>();
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_view, list);
listView.setAdapter(adapter);
DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("Car Wash");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
list.add(snapshot.getValue().toString());
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
What you're seeing is the toString() output of the value a Firebase DataSnapshot that represents an object with multiple values.
You'll want to get the individual values from that snapshot, and display their values with something like this:
String name = snapshot.child("Name").getValue(String.class);
String phoneNr = snapshot.child("Phone Number").getValue(String.class);
list.add(name+" ("+phoneNr+")");
In Firebase, I list my data by auto increment. However, when i any data is deleted, i can't new data added. Updating is being made on the last added data. I need a solution for this.
Firebase
My Source:
public class MainActivity extends AppCompatActivity {
EditText name_et;
Button button_save;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
long autoincrementid =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name_et = findViewById(R.id.aaaa);
button_save = findViewById(R.id.btnsave);
databaseReference = firebaseDatabase.getInstance().getReference().child("Data");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists());
autoincrementid=(snapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a = name_et.getText().toString();
databaseReference.child(String.valueOf(autoincrementid+1)).setValue(a);
Toast.makeText(MainActivity.this, "+++++", Toast.LENGTH_SHORT).show();
}
});
}
}
Right now you use the count of children to determine what the next number is. That works well if all sequential indexes are occupied, but (as you found) not when you delete one of more indexes in there.
The proper solution in that case depends on what you want to happen. I know of these general use-cases:
You want the list to behave like an array, which means that when you remove #3 in your JSON, the #4 and #5 actually get a new index. This will require you to change all other items when you remove one. For more on this see the answer I gave just now to another question: Firebase Remove with Javascript
You want to have an always increasing sequential index, typically referred to as a sequence or auto-increment values in relational databases. If you want this, you'll have to store the latest index that you handed out somewhere separate in the database and transactionally update that whenever you add an item to the list.
You want to put new items at the first available index, reusing the indexes of any deleted nodes. This seems to be your use-case, so we'll look at that further below.
Possible code for a solution that finds the first available id:
databaseReference = firebaseDatabase.getInstance().getReference().child("Data");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
int autoincrementid = 0;
do {
autoincrementid++;
} while (snapshot.hasChild(""+autoincrementid));
snapshot.child(""+autoincrementid).setValue("New value");
})(
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
A few notes on this code:
I didn't run it, so there may well be some minor errors in there. If you get any of those, please try to figure them out on your own and edit the answer to include the solution.
You probably should use a transaction here to ensure there are no conflicting updates. The logic of the loop will be the same though.
I have a method in my FollowersActivity class getFriendsAttendingEvent(); which returns the number of users that adhere to two specific criteria. Now, those users populate a list when I click on a TextView which I have in my Adapter class PostAdapter.
I need to get that number (quantity) of users that are in the list and I want to put it in the TextView in my PostAdapter class. I want to do something like holder.textView.setText(*list.size()), but how can I get that number from my FollowersActivity over to my PostAdapter class?
I know from the Adapter class I transfer data between the two classes by using Intent, but to go the other way around, would I have to create an interface or something? SharedPreferences perhaps? I don't know...
How would I send this line, String number = String.valueOf(mIdList.size()); over to my PostAdapter? This is the number that I need.
FollowersActivity
private void getFriendsAttendingEvent() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Attending Event").child(mPostId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mIdList.add(snapshot.getKey());
}
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Following").child(mFirebaseUser.getUid());
reference1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mIdList1.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (String id : mIdList) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (Objects.equals(snapshot.getKey(), id)) {
mIdList1.add(snapshot.getKey());
}
}
}
}
if (mIdList1.size() > 0) {
String number = String.valueOf(mIdList.size());
Log.d("NUMBEROFUSERS", number);
showUsers();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
PostAdapter
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPost.get(position);
holder.friendsAttendingEvent.setOnClickListener(v -> {
Intent intent = new Intent(mContext, FollowersActivity.class);
intent.putExtra("id", post.getPostid());
intent.putExtra("postid", post.getPostid());
intent.putExtra("publisherid", post.getPublisher());
intent.putExtra("title", "Friends Attending");
mContext.startActivity(intent);
});
So what I have understood so far is that,
You have a PostAdapter (that displays data related to a post just like in most of the social media applications) and this Adapter has a TextView that represents the number of followers.
So, the navigation structure might be like this:
PostAdpater --- (Click on the TextView) ---> FollowersActivity
By Clicking the TextView representing the number of followers we shift to the FollowersActivity, and there you might be displaying the details of Followers. But the problem is, that you are fetching the data on the FollowersActivity where as you required it before the navigation on the PostAdapter.
The Only Simple Solution that I am able to figure out is that you move your query function getFriendsAttendingEvent() from FollowersActivity to PostAdapter, fetch the count of followers in the adapter and then pass that count to the FollowersActivity through Intent in case you do not want to re fetch data.
PostAdapter -------> FollowersActivity
(count required here) (fetching here)
PostAdapter -------> FollowersActivity
(fetch count here) (pass data here through Intent of refetch it)
Please tell me if didn't understood the problem correctly i might come up with a better solution
I'm calling addValueEventListener inside the button click, but this method only reads the last item in the node. I want to read all the child value in the node What went wrong here?
btnorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
SelectedItems si=dataSnapshot1.getValue(SelectedItems.class);
si.getItemname();
Toast.makeText(MyBookedItems.this, ""+si.getItemname(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
I think you can create an array list and put all snapshot data into it, and then you can find the last data of the list with the value you find by subtracting one from the length of the list. Sorry for my bad English :( I have tried to explain in the solution in the code below)
ArrayList<SelectedItems> selectedItems = new ArrayList<SelectedItems>();
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
{
SelectedItems si=dataSnapshot1.getValue(SelectedItems.class);
selectedItems.add(si);
}
selectedItems.get(selectedItems.size());
It's read all the values but I got the output as a Toast message, because of that I only see the last value)
I am trying to make it so that when a user creates an open game, in my Firebase Database the name of the game is the size of the list. So the very first game created the name of it will = 0, and if another user creates a game then the game will be labeled 1 and so on.
I have it set up right now so that the games are labeled the size of the game list, but the list isn't really updating. The games keep getting called '0' because it thinks the list is empty even though I have visual confirmation in the app that there are items being added to the list.
So my question is: How can I make it so the list continuously updates each time a game is added, and how can I make it so that it updates for all users and not just the user who created the game?
This is what I have setup right now. Here are the variables I am using for the list and the integer getting the list size
ArrayList<String> openGames = new ArrayList<>();
int gameSlot = openGames.size();
Here is what I use to name the game when it is created.
gameMaker = new GameMaker(hp.uid, userName, wagerD, gameSlot);
FirebaseDatabase.getInstance().getReference("FCGames").child(Integer.toString(gameSlot))
.setValue(gameMaker).addOnCompleteListener...
And this is what I have to add the game to the list.
cgRef.child(Integer.toString(gameSlot)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
openGames.add(userName);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
So again my question is how can I make this list update correctly and how can I make it update for all users on the app?
Edit
Here is what I did with my onChangeData
cgRef.child(Integer.toString(gameSlot)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
wager = (String) dataSnapshot.child("wager").getValue();
gameSlot = openGames.size();
adapter.notifyDataSetChanged();
}
and now the openGames.add is in my createGameLobby method.
FirebaseDatabase.getInstance().getReference("FCGames").child(Integer.toString(gameSlot))
.setValue(gameMaker).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
openGames.add(userName);
Toast.makeText(FlipCoinLobby.this, "Game creation successful.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FlipCoinLobby.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
^^ that is just the important snippit from the method. And then I have an onClickListener that creates that calls that method when a button is pressed
In below code segment, you did that openGames.add(username) in onDataChange listener. I think it is an incorrect use of this ondatachange function
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
openGames.add(userName);
adapter.notifyDataSetChanged();
}
please use this to get data from db and update your data. Then push your data to db. You didn't use snapshot value also. You can get most recently updated data from dataSnapshot . Use it to update user data then push it to db