Now im trying to create my first Android app.
I'm currently working on a view name Bands which is supposed to create a list (imported from Firebase Database) and link it to a ListView.
As you can see, i have a link to print out the whole bandsList, that way i know the list imported well, and it is...but the ListView is not updated according to the bandsList, so im guessing the problem is in the adapter.
public class Bands extends AppCompatActivity {
ListView listView;
ArrayList<String> bandsList = new ArrayList<>();
ArrayAdapter<String> bandsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bands);
listView = findViewById(R.id.bandsListView);
bandsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, bandsList);
listView.setAdapter(bandsAdapter);
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Bands");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot band : dataSnapshot.getChildren()) {
String bandName = band.child("Name").getValue(String.class);
bandsList.add(bandName);
System.out.println("bandsList :" + bandsList);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//String BandName =dataSnapshot.getValue(String.class);
for (DataSnapshot band : dataSnapshot.getChildren()) {
String bandName = band.child("Name").getValue(String.class);
System.out.println(bandName);
bandsList.add(bandName);
System.out.println(bandsList);}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Just add bandsAdapter.notifyDataSetChanged() after the Firebase-Callback:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot band : dataSnapshot.getChildren()) {
String bandName = band.child("Name").getValue(String.class);
bandsList.add(bandName);
System.out.println("bandsList :" + bandsList);
}
bandsAdapter.notifyDataSetChanged();
}
You need to tell the adapter to update the list in both
onDataChange() and onChildAdded() using bandsAdapter.notifyDataSetChanged();
Related
I have the above format in firebase realtime database
I need to get data in arraylist
public class EmojiView extends AppCompatActivity {
FirebaseUser firebaseUser;
DatabaseReference reference;
ArrayList<String> images = new ArrayList<>();
private void getImagesfromDB() {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("stickers");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
images.add(data);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_view);
getImagesfromDB();
}
}
I get the urls in data variable in OnDataChangemethod, but i am not able to assign those values to images arraylist
Try this:
Change your reference to this:
reference = FirebaseDatabase.getInstance().getReference("stickers").getChildren();
And then loop through the snapshots (which should be the children of "stickers") this way:
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot item : snapshot){
stickers.add(item.getValue(String.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
i want to get listarray of data in firebase and put it in my listview , but i cant add the condition ..
this is the firebase.
"Sendmail" : {
"-LkYHbH6FfiR-8ua7RQS" : {
"deskripsi" : "coba",
"perihal" : "coba",
"username_from" : "rezkysaputra96",
"username_to" : "hendra_admin"
},
"-LkbF2gEg6Q-cre8gSnd" : {
"deskripsi" : "example2",
"perihal" : "example2",
"username_from" : "rezkysaputra96",
"username_to" : "hendra_admin"
},
"-LkbF7YTY5yr7nMlAZss" : {
"deskripsi" : "example3",
"perihal" : "example3",
"username_from" : "rezkysaputra96",
"username_to" : "nurhamid123"
}
}
and this is my code ,this is get all data from "sendmail" , but i want get data from "sendmail" with some condition of value..
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Sendmail");
ListView listView = (ListView) view.findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>( getActivity().getApplicationContext(), android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
String value = dataSnapshot.getValue(Sendmail.class).toString();
arrayList.add(value);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
how can i get list data from sendmail where username_to = hendra_admin ?
thanks , im new in firebase and java.
You can use the Query class to filter your query. See the Firebase reference page for working with lists of data. Simply put, you need to order your query -using one of the orderBy.. methods- first and then filter it. In your case, you need to use orderByChild because you want to filter your result based on the child username_to. Then use equalTo to filter the result. This should returns what you want:
Query query = databaseReference.child("Sendmail").orderByChild("username_to").equalTo("hendra_admin");
This is the solution that i've found on this forum too .
thanks .
this is my code now .
public class OutboxFragment extends Fragment {
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
public String getusername;
public String uid;
FirebaseAuth firebaseAuth;
public OutboxFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_outbox, container, false);
firebaseAuth = FirebaseAuth.getInstance();
uid = firebaseAuth.getCurrentUser().getUid();
dapatdatauser(uid);
// Inflate the layout for this fragment
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Sendmail").orderByChild("username_from").equalTo("rezkysaputra96");
ListView listView = (ListView) view.findViewById(R.id.listview);
arrayAdapter = new ArrayAdapter<String>( getActivity().getApplicationContext(), android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Map data = (Map ) dataSnapshot.getValue();
String name = (String) data.get("perihal");
arrayList.add(name);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
public void dapatdatauser(String iduser){
// Mendapatkan DataUsers Berdasarkan uid sesuai login
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference query = reference.child("DataUsers").child(iduser);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Memasukkan data kedalam variabel username
getusername = dataSnapshot.child("username").getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
For my chat application, I have saved EditText data to firebase but not I am not able to display the same in ListView. I am able to see the EditText data in Firebase database and I want to retrieve it in a ListView. Anybody can help me?
public class Chatbox extends AppCompatActivity {
private DatabaseReference databaseReference;
private Button btnsend;
private EditText editText;
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbox);
databaseReference = FirebaseDatabase.getInstance().getReference();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
btnsend = findViewById(R.id.sendbutton);
editText = findViewById(R.id.typemessage);
listView = findViewById(R.id.listmessages);
btnsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.child("Chat").child("Name").push().setValue(editText.getText().toString());
}
});
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getKey();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
catch (Exception ex)
{
Toast.makeText(Chatbox.this, "Error " + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try this
FirebaseDatabase.getInstance()
.getReference("Chat")
.child("Name")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<String> chatMessages = new ArrayList<>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
try {
String chatMessage = String.valueOf(dataSnapshot.child(dataSnapshot1.getKey()).getValue());
chatMessages.add(chatMessage);
} catch (DatabaseException e) {
e.printStackTrace();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
callback.onFailure(null);
}
});
i guess you want to retrive data not the key:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DatabaseReference chatreference=databaseReference.child("Chat");
chatreference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.child("Name").getValue();
Toast.makeText(Chatbox.this, "keys " + chatmsg, Toast.LENGTH_SHORT).show();
arrayList.add(chatmsg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
or want you to store both in a array list key and value together?
You're adding the messages to the database with:
databaseReference.child("Chat").child("Name")
That means you must also read the messages from the same path:
databaseReference.child("Chat").child("Name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String chatmsg = snapshot.getValue(String.class);
arrayList.add(chatmsg);
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()l
}
});
The changes:
Listen to the same node as you're adding the messages to.
Removed the nested listener, which is not needed.
Get the value from each child snapshot, instead of trying to read a non-existing Name property.
Removed the try...catch as the default behavior is to write messages to logcat, which is more useful than showing them in a toast.
Implemented onCancelled, because you should never ignore errors.
Hi I'm trying to display certain data on my listview based on item selected from a spinner. This is how the display page currently looks. It's reading all the data from the node. Because "Running" is selected on the spinner above, I want the list view to only show Running.
Here is the code i'm using to read all the data.
#Override
protected void onStart() {
super.onStart();
//reading data to listview, every time its saved
currentUserDB2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cardiosList.clear();
for(DataSnapshot cardioHistorySnapshot : dataSnapshot.getChildren()){
Cardio cardio = cardioHistorySnapshot.getValue(Cardio.class);
cardiosList.add(cardio);
}
CardioHistoryList adapter = new CardioHistoryList(Cardio_History.this, cardiosList);
ListViewCardioHistory.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Working code
spinnerCardioHistory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String name = spinnerCardioHistory.getSelectedItem().toString();
currentUserDB2.orderByChild("detailCategory").equalTo(name).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cardiosList.clear();
for (DataSnapshot cardioHistorySnapshot : dataSnapshot.getChildren()){
Cardio cardio = cardioHistorySnapshot.getValue(Cardio.class);
cardiosList.add(cardio);
}
CardioHistoryList adapter = new CardioHistoryList(Cardio_History.this, cardiosList);
ListViewCardioHistory.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If you want only the word Running to be displayed then do the following:
String text = spinner.getSelectedItem().toString();
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference currentUserDB2=FirebaseDatabase.getInstance().getReference().child("Cardio").child(user.getUid());
currentUserDB2.orderByChild("detailCategory").equalTo(text).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
cardiosList.clear();
for(DataSnapshot cardioHistorySnapshot : dataSnapshot.getChildren()){
String category=cardioHistorySnapshot.child("detailCategory").getValue().toString();
cardiosList.add(category);
}
CardioHistoryList adapter = new CardioHistoryList(Cardio_History.this, cardiosList);
ListViewCardioHistory.setAdapter(adapter);
First you get the select texted that is in the spinner String text = spinner.getSelectedItem().toString();
then you add it in the query orderByChild("detailCategory").equalTo(text) and then retrieve from the database and it will only add the word that is selected in the spinner which is "Running".
I have this database:
In Activity A, I click on a class(listitem) and then pass the id of that class to this activity like this:-
so = getIntent().getStringExtra("send_id");
So right now I have the ClassId in this activity inside so. Then I run this query:
myref= FirebaseDatabase.getInstance().getReference().child("ClassStudent");
Query fk=myref.orderByChild("ClassId").equalTo(so);
fk.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
student=dataSnapshot.child("Studentid").getValue().toString();
//a breakpoint here gives student=oyvEbB0128Y90ADzXnL0UwCUy0Z2
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
So in the query I want all the students id that have that classid orderByChild("ClassId").equalTo(so)
Then I create a FirebaseRecycleradapter
FirebaseRecyclerAdapter<Info,ViewHolder> recyclerAdapter=new FirebaseRecyclerAdapter<Info,ViewHolder>(Info.class, R.layout.row, ViewHolder.class, fk) {
#Override
protected void populateViewHolder(final ViewHolder holder, Info model, int position) {
holder.title.setText(student); //a breakpoint here gives student = 7AnhQ7pRwhXDRqytjSUkoJrOB253
}
}
Now the data is appearing(on phone screen) like this:
Result
7AnhQ7pRwhXDRqytjSUkoJrOB253
7AnhQ7pRwhXDRqytjSUkoJrOB253
The above student id is appearing twice, instead it should be:
It should be
7AnhQ7pRwhXDRqytjSUkoJrOB253
oyvEbB0128Y90ADzXnL0UwCUy0Z2
Since both those students are in that class.
I have also overridden, getItemId and getItemViewType
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classStudentRef = rootRef.child("ClassStudent");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Studentid = ds.child("Studentid").getValue(String.class);
Log.d("TAG", Studentid);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
classStudentRef.addListenerForSingleValueEvent(eventListener);
The output will be:
7AnhQ7pRwhXDRqytjSUkoJrOB253
oyvEbB0128Y90ADzXnL0UwCUy0Z2
Edit: To get the name of the student of the coreponding stundet if you need to query your database twice. So, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classStudentRef = rootRef.child("ClassStudent");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String Studentid = ds.child("Studentid").getValue(String.class);
Log.d("TAG", Studentid);
DatabaseReference studentIdRef = rootRef.child("Student").child(Studentid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
studentIdRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
classStudentRef.addListenerForSingleValueEvent(eventListener);