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.
Related
In my ChatListActivity, I am getting emails of users and showing them in a listView using Firebase. There is value in Firebase because when the arraylist is showing its data when I use log, but isn't showing in ListView. Please help.
public class ChatListActivity extends AppCompatActivity {
ListView userListView;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> users = new ArrayList<>();
FirebaseAuth mAuth;
DatabaseReference databaseReference;
Button signOut;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_list);
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
userListView = findViewById(R.id.userListView);
signOut = findViewById(R.id.signOut);
databaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
String email = dataSnapshot.child("email").getValue().toString();
if (!email.equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
users.add(email);
Log.i("Log", Arrays.toString(new ArrayList[]{users}));
}
}
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ChatListActivity.this, "Failed to load users", Toast.LENGTH_SHORT).show();
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
Intent intent = new Intent(ChatListActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
Here is my log.
Do set an empty adapter before network call, like this
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
after you receive original response, reset the adapter with new data. That should work.
now "users" will have some data
arrayAdapter = new ArrayAdapter<>(ChatListActivity.this, android.R.layout.simple_list_item_1, users);
userListView.setAdapter(arrayAdapter);
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.
I'm trying to return the key and value from my Firebase Database and insert it into a RecycleView adapter but the values won't show up in the app.
I can't wrap my head around this whatsoever.
I tried to show the values in a Toast and it worked but why won't the values be inserted into the RecycleView adapter?
This is the code.
public class test extends AppCompatActivity {
TextView textView;
Button button;
String phone;
String n;
String a;
FirebaseAuth mAuth;
MyRecyclerViewAdapter adapter;
ArrayList<String> info;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Bundle b = new Bundle();
b = getIntent().getExtras();
phone = b.getString("number");
textView = findViewById(R.id.textV);
button = findViewById(R.id.signoutButton);
mAuth = FirebaseAuth.getInstance();
textView.setText(textView.getText().toString() + " as " + phone);
info = new ArrayList<>();
FirebaseDatabase myRef = FirebaseDatabase.getInstance();
DatabaseReference sRef = myRef.getReference("users");
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerView recyclerView = findViewById(R.id.rvInfo);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, info);
adapter.setClickListener(new MyRecyclerViewAdapter.ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(test.this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
});
recyclerView.setAdapter(adapter);
}
}
You can get this using following code
sRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnap : dataSnapshot.getChildren()) {
if (childSnap.getKey().equals(phone)) {
for (DataSnapshot c : childSnap.getChildren()) {
n = c.getKey();
a = c.getValue().toString();
info.add(n);
info.add(a);
}
}
}
notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You have to add notifyDataSetChanged(); after you fill ArrayList from firebase. Because it's take time to load data from firebase. And your adapter initialised before fill ArrayList from firebase.
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()