DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("User Allergens").child(uid);
what do i need to add after .child(UID)?
the code I have:
ArrayList<String> list = new ArrayList<>();
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, list );
listView.setAdapter(adapter);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("User Allergens").child(uid);
reference.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 error) {
}
});
picture of data structure in firebase, have a look for a clear view.
As I see in your screenshot, under the following reference:
FirebaseRoot -> User Allergens -> UID
You have a few children of type String, that contain some values like Lactose, Gluten or Sugar. To get all these values and use them in your adapter, please use the following lines of code:
ListView listView = (ListView) findViewById(R.id.list_view);
List<String> list = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, list);
listView.setAdapter(arrayAdapter);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("User Allergens").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot alergenSnapshot : task.getResult().getChildren()) {
String alergen = alergenSnapshot.getValue(String.class);
list.add(alergen);
}
adapter.notifyDataSetChanged();
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
If task.getException().getMessage() yelds no errors, then the result of the above code will be a ListView filled up with alergen names from your Firebase Realtime Database.
Related
I am trying to fill a spinner with categories, I manage to iterate every category in my database and add it to the spinner but I need to fetch only distinct values, see this image;
This is my code;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
final List<String> categorySpinner = new ArrayList<>();
for (DataSnapshot childSpinner : snapshot.getChildren()) {
String spinnerCat = childSpinner.child("category").getValue(String.class);
categorySpinner.add(spinnerCat);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(LineChartActivity.this, R.layout.spinner_item, categorySpinner);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner_2.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
It's simple, simply change the line:
categorySpinner.add(spinnerCat);
to
if (!categorySpinner.contains(spinnerCat)) {
categorySpinner.add(spinnerCat);
}
Happy coding.
-Quiz
-MCQ
-Question
-1831
-783444
-//still got data
-234567
-//still got data
Above is my Firebase realtime database and I want only show the 783444 and 234567 to my ListView and clickable to next activity.
Please give some advise to solve my problem. Thank you very much.
To get only those keys, 783444 and 234567 in a ListView, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Quiz").child("MCQ").child("Question").child("1831");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
list.add(key);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Go to next activity
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
Here is the image of my Firebase database setup:
I'm trying to program a simple notes application, I'm able to save everything to Firebase but struggling to retrieve the information.
A child of the user IDis randomly generated which is causing me issues when trying to retrieve the data. The below code is how im saving all the data to the Firebase database.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_reports);
findViewById(R.id.saveNoteButton).setOnClickListener(saveReport);
progressReportTitle = findViewById(R.id.progressReportTitle);
progressReportContent = findViewById(R.id.progressReportContent);
fAuth = FirebaseAuth.getInstance();
fProgressReportsDatabase = FirebaseDatabase.getInstance().getReference().child("ProgressReports").child(fAuth.getCurrentUser().getUid());
findViewById(R.id.loadNoteButton).setOnClickListener(loadReports);
}
View.OnClickListener saveReport = new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = progressReportTitle.getText().toString().trim();
String content = progressReportContent.getText().toString().trim();
if (title.isEmpty()) {
progressReportTitle.setError("Please Enter a title for this report");
progressReportTitle.requestFocus();
} else if (content.isEmpty()) {
progressReportContent.setError("No content within report");
progressReportContent.requestFocus();
} else {
saveReportToDB(title, content);
}
}
};
private void saveReportToDB(String title, String content) {
if (fAuth.getCurrentUser() != null) {
final DatabaseReference newProgressReportRef = fProgressReportsDatabase.push();
final Map progressReportMap = new HashMap();
progressReportMap.put("title", title);
progressReportMap.put("content", content);
progressReportMap.put("timestamp", ServerValue.TIMESTAMP);
And below is how im attempting to load this data into a listview on a separate activity, with no luck,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mListView = (findViewById(R.id.progressList));
fAuth = FirebaseAuth.getInstance();
fFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = FirebaseDatabase.getInstance().getReference().child("ProgressReports").child(fAuth.getCurrentUser().getUid());;
FirebaseUser user = fAuth.getCurrentUser();
userID = user.getUid();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot){
for(DataSnapshot ds : dataSnapshot.getChildren()){
ReportInformation rInfo = new ReportInformation();
rInfo.setTitle(ds.child(userID).child("title").getValue(ReportInformation.class).getTitle());
rInfo.setContent(ds.child(userID).child("content").getValue(ReportInformation.class).getContent());
//rInfo.setTimestamp(ds.child(userID).child("timestamp").getValue().toString());
ArrayList<String> array = new ArrayList<>();
array.add(rInfo.getTitle());
array.add(rInfo.getContent());
//array.add(rInfo.getTimestamp());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
mListView.setAdapter(adapter);
}
}
What am I doing wrong, and how can I query the database for the HashMap which is randomly generated?
Thanks guys
To display all titles of all those objects in a ListView, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("ProgressReports").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String title = ds.child("title").getValue(String.class);
list.add(title);
Log.d("TAG", title);
}
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
Your list will contain two titles:
Test
Test
More information here if you want to use a model class.
I am trying to get all keys under a Value and generate a popup for them. But I don't get how. I tried a lot of "for" statements but could not figure it out.
My code at the moment:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Anzeigen");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot:dataSnapshot.getChildren())
{
RecyclerView recyclerView = findViewById(R.id.anzeigen_list);
final List<generater> mList = new ArrayList<>();
RecyclerView.Adapter adapter = new generater_anzeigen_setter(this,mList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mList.add(new generater(Name , Was , Preis));
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
This is my database:
try this:
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
final List<generater> mList = new ArrayList<>();
for(DataSnapshot ds:dataSnapshot.getChildren()){
String name,was,preis;
for(DataSnapshot childSnapShot:ds.getChildren()){
if(childSnapShot.getKey().equals("Name")){
name=childSnapShot.getValue().toString();
}
if(childSnapShot.getKey().equals("Was")){
was=childSnapShot.getValue().toString();
}
if(childSnapShot.getKey().equals("Preis")){
preis=childSnapShot.getValue().toString();
}
}
generater generater = new generater(name , was , preis);
mList.add(generater);
}
RecyclerView recyclerView = findViewById(R.id.anzeigen_list);
final List<generater> mList = new ArrayList<>();
RecyclerView.Adapter adapter = new generater_anzeigen_setter(this,mList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListView listView = (ListView) rootView.findViewById(R.id.usersList);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, al);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
name = ds.child("Name").getValue().toString();
// Log.d("TAG", name);
al.add(name);
String list_user_id = getRef(position).getKey();
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"Please Check Your Internet Connection",Toast.LENGTH_SHORT).show();
}
};
usersRef.addListenerForSingleValueEvent(eventListener);
In the line of string list_user_id = getRef(Position).getKey(): I guess this is returning null because when the user clicks on the item in listview
usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserDetails.chatWith = al.get(position);
Intent intent = new Intent(getActivity(), Chat.class);
intent.putExtra("visit_user_id",list_user_id);
intent.putExtra("user_name",name);
startActivity(intent);
}
});
return rootView;
He will be directed to chat activity... as soon as i open chat avtivity im getting null pointerexception on this line
MessageRecieverId = getIntent().getExtras().get("visit_user_id").toString();
Where have i gone wrong? trying to make a chat application so need to fetch the unique id of the user...
Database screenshot http://ibb.co/cwOQtx
getting a null error again
rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
}
error in the line rootref.chil("messages")........
Error- http://ibb.co/h4D2dx
Change the code( inside of ValueEventListener) :
String list_user_id = getRef(position).getKey();
to this:
String list_user_id = ds.getKey();
for(DataSnapshot ds : dataSnapshot.getChildren()) ds here is iterating inside the direct children which are the unique ids, then by using the above you will be able to retrieve the unique ids.
Also according to the firebase docs:
getRef() does not accept any parameters.
more info here:-
https://firebase.google.com/docs/reference/android/com/google/firebase/database/DataSnapshot.html#getRef()