read data per ID from firebase into spinner - java

I would like read data from firebase into spinner, and the spinner should contain data per ID. There is two spinner, color & size, but what I got is all data from all ID. How i can fix this issue?
The firebase data structure like image below :
and here is my code :
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference AttrReference = reference.child("Products").child("Attribut");
....
private void getAttributProduct() {
AttrReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<>();
colorList = new ArrayList<>();
sizeList = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot child : snapshot.getChildren()) {
AttrProduk attr = child.getValue(AttrProduk.class);
list.add(attr);
colorList.add(attr.getColor());
sizeList.add(attr.getSize());
showSpinnerSize(sizeList);
showSpinnerColor(colorList);
showStock(attr.getStock());
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSpinnerSize(List<String> dataSize) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, dataSize);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spSize.setAdapter(adapter);
}
private void showSpinnerColor(List<String> dataColor) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item, dataColor);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spColor.setAdapter(adapter);
}
private void showStock(String data) {
stock.setText(data+" Pcs");
}
And here is what i got, based on database it should get data per ID :

If you want the spinner to show data related to a key, then you need to do a query:
DatabaseReference AttrReference = reference.child("Products").child("Attribut");
Query query=AttrReference.orderByKey().equalTo(key_id);
query.addValueEventListener(new ValueEventListener() {..}
https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query.html#orderByKey()

Related

Android Firebase Query for Multiple values

I want to fetch the all uid's of the doctor whose category is "abc"(example) and then store those retrieved uid's into an array list.
I want same results as displayed by the below sql query:
select uid from doctors where category = "abc";
Code for next activity is written below
private void loadDoctors() {
ArrayList<String> uid = getIntent().getStringArrayListExtra("doctor_list");
for (int i =0;i<uid.size();i++){
DatabaseReference doctors = FirebaseDatabase.getInstance().getReference("Doctors").child(uid.get(i));
Adapter = new FirebaseRecyclerAdapter<DoctorModel, DoctorViewHolder>(
DoctorModel.class,
R.layout.doctors_home,
DoctorViewHolder.class,
doctors
) {
#Override
protected void populateViewHolder(final DoctorViewHolder viewHolder, final DoctorModel model, int position) {
viewHolder.doctor_name.setText(model.getName());
Glide.with(Doctors.this).load(model.getProfileimage()).into(viewHolder.doctor_image);
viewHolder.qualification.setText(model.getQualification());
viewHolder.rating.setText(model.getRating());
}
};
Adapter.notifyDataSetChanged();
doctors_list.setAdapter(Adapter);
}
To solve this, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference doctorsRef = rootRef.child("Doctors");
Query categoryQuery = doctorsRef.orderByChild("category").equalTo("Cardiology");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> uidList = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
uidList.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
categoryQuery.addListenerForSingleValueEvent(valueEventListener);
At the end, you'll have a list full of uids. One more thing to note, because Firebease API is asynchronous, you will be able to use that list only inside onDataChange() method.

Firebase Not Populating List

I am building an Android shopping list app following a Angga Risky tutorial.
Code running Error free, but the list I have created is not being populated by the firebase real-time database it is connected to. Below is the mainactivity
public class MainActivity extends AppCompatActivity {
TextView titlepage, subtitlepage, endpage;
DatabaseReference reference;
RecyclerView ourlist;
ArrayList < MyList > list;
ListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
titlepage = findViewById(R.id.titlepage);
subtitlepage = findViewById(R.id.subtitlepage);
endpage = findViewById(R.id.endpage);
//working with data
ourlist = findViewById(R.id.ourlist);
ourlist.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList < MyList > ();
//get data from firebase
reference = FirebaseDatabase.getInstance().getReference().child("compshopper3");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//set code to retrieve data and replace layout
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
MyList p = dataSnapshot1.getValue(MyList.class);
list.add(p);
}
listAdapter = new ListAdapter(MainActivity.this, list);
ourlist.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// set code to show an error
Toast.makeText(getApplicationContext(), "Dude Where's My Data???", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is look at the firebase data
Here is a shot of the emulator output.
First change the reference to refer to the parent node:
reference = FirebaseDatabase.getInstance().getReference().child("CompShopperApp");
Then remove the for loop inside onDataChange() and make sure that your model class contains the fields price1, price2, price3 and itemtitle:
reference.addValueEventListener( new ValueEventListener () {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyList p = dataSnapshot.getValue(MyList.class);
list.add(p);
listAdapter = new ListAdapter(MainActivity.this, list);
ourlist.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// set code to show an error
Toast.makeText(getApplicationContext(), "Dude Where's My Data???", Toast.LENGTH_SHORT).show();
}
In addition to #peter-haddad's answer, make sure your firebase database rules allow you to access the data without authentication, in case you're trying to do that (which we usually do during dev testing).
Firebase console -> Database (Realtime Database) -> Rules ->
{
"rules": {
".read": true,
".write": true
}
}

how to get all child nodes from firebase database?

this is my structure. i am trying to code a scoreboard for my app but i cant get the username & score. i want to safe that username & score in a sorted list to get the top 10.
this is my code: i onle get the usernames.
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
for (DataSnapshot as : dataSnapshot.getChildren()) {
String userkey= as.getKey();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});
Try the following:
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Userlist = new ArrayList<String>();
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
String userkey = dsp.getKey();
String scores = dsp.child("scorehigh").getValue().toString();
Userlist.add(userkey); //add result into array list
}
}
un.setText(Userlist.get(2));
}
#Override
public void onCancelled(DatabaseError error) {
}
});
The reference is at Users then you need to loop twice to be able to access the attributes scorehigh and username

Android firebase - show specific data

I'm trying to create a Firebase Realtime database project in which the data stored is either type A or type B, etc. This is how it looks like on the console:
Firebase Database
The user can then add more posts, of which are saved to the database then displayed on a ListView.
My Code
final DatabaseReference room = FirebaseDatabase.getInstance().getReference().getRoot();
chatRoomAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, chatList);
lvChatRoom.setAdapter(chatRoomAdapter);
btnAddChatRoomMa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strChatRoomName = etChatRoom.getText().toString();
etChatRoom.setText("");
Map<String, Object> chatMap = new HashMap<>();
chatMap.put(strChatRoomName + " -TYPEA", "");
room.updateChildren(chatMap);
}
});
room.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
Set<String> set = new HashSet<>();
while (iterator.hasNext()) {
set.add(((DataSnapshot) iterator.next()).getKey());
}
chatList.clear();
chatList.addAll(set);
chatRoomAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I only want to show for instance, TYPEA (on the database), without displaying the rest. How can I achieve this?
If you want to display only the value of the property TYPEA, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("fruit-TYPEA");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String fruitTYPEA = dataSnapshot.getValue(String.class);
Log.d("TAG", fruitTYPEA);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output will be: orange.

I want to retrieve all user's UID from Firebase user array and store it into Arraylist

databaseReference.child("user").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String requests = postSnapshot.getValue(String.class);
req.add(requests);
adapter = new ChallengeSuggestionAdapter(getActivity(), req);
recyclerView.setAdapter(adapter);
}
}
Thanks for helping :)
You're recreating the adapter within the loop. Don't do that.
final List<String> req = new ArrayList<>();
final ChallengeSuggestionAdapter adapter = new ChallengeSuggestionAdapter(getActivity(), req);
recyclerView.setAdapter(adapter);
databaseReference.child("user").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
req.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String requests = postSnapshot.getValue(String.class);
req.add(requests);
}
recyclerView.notifyDataSetChanged();
}
});
Also, I don't think getValue(String.class) is correct, but you've not expanded your Firebase nodes, so hard to say.
If you want that UUID, you would use req.add(postSnapshot.getKey())
Create GenericTypeIndicator to pass value from DataSnapshot.getValue() parameter.
Look:-
GenericTypeIndicator<List<String>> typeIndicator = new GenericTypeIndicator<List<String>>() {};
List<String> stringArrary = dataSnapshot.getValue(typeIndicator );
Please Use getKey if you want the uid and take your recyclerview adapter from the loop. try using addValueEventListener
databaseReference.child("user").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
req.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String requests = postSnapshot.getKeyString.class);
req.add(requests);
}
adapter = new ChallengeSuggestionAdapter(getActivity(), req);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Categories