Retrieving data from Firebase but not showing - android

This is my firebase database from where I want to retrieve all the names of universities in ListView click here to see image
myRef= FirebaseDatabase.getInstance().getReference();
myRef.child("Universities").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
database c = postSnapshot.getValue(database.class);
final String name = c.getuniName();
userNameList.add(name);
final ArrayAdapter<String> mutahirAdapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1 , userNameList);
mListView.setAdapter(mutahirAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Database Class
I added data directly in Firebase now I am not getting the data in the ListView i wanted to retrieve all the child's of universities in ListView
package com.mutahir.futureguide;
public class database {
String Name;
public String uniName(String Name) {
this.Name= Name;
return Name;
}
public String getuniName() {
return Name;
}
public void setuniName(String Name) {
this.Name = Name;
}
}

Hope it worked!
myRef= FirebaseDatabase.getInstance().getReference();
myRef.child("Universities").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
final String name = postSnapshot.getValue("name").toString();
userNameList.add(name);
}
if(!userNameList.isEmpty()){
final ArrayAdapter<String> mutahirAdapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1 , userNameList);
mListView.setAdapter(mutahirAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Dynamic Expandable Recyclerview List Failing

I'm new to Android and I know this might be a piece of cake but I'm struggling.
I was trying to create a dynamic expandable recycler view using firebase realtime database but the data is not displaying properly.
I'm passing a string from one activity to another and comparing the string to the database field and then displaying it's child components but I don't know where I'm failing.
I want to display the Parent and child field by comparing the name field with the value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_detail);
//string value from another activity
String value = getIntent().getExtras().getString("name");
recycler_view = (RecyclerView) findViewById(R.id.recycler_expand);
recycler_view.setLayoutManager(new LinearLayoutManager(this));
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference parentReference = database.getReference().child("Tutors");
//comparing
parentReference.equalTo(value).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ParentList> Parent = new ArrayList<>();
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String ParentKey = snapshot.getKey().toString();
snapshot.child("title").getValue();
DatabaseReference childReference =
FirebaseDatabase.getInstance().getReference().child(ParentKey);
childReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChildList> Child = new ArrayList<>();
for (DataSnapshot snapshot1:dataSnapshot.getChildren())
{
final String ChildValue = snapshot1.getValue().toString();
snapshot1.child("title").getValue();
Child.add(new ChildList(ChildValue));
}
Parent.add(new ParentList(ParentKey, Child));
DocExpandableRecyclerAdapter adapter = new DocExpandableRecyclerAdapter(Parent);
recycler_view.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Database Structure
ChildList.java
public class ChildList implements Parcelable {
private String title;
public ChildList(String title) {
this.title = title;
}
protected ChildList(Parcel in) {
title = in.readString();
}
public static final Creator<ChildList> CREATOR = new Creator<ChildList>() {
#Override
public ChildList createFromParcel(Parcel in) {
return new ChildList(in);
}
#Override
public ChildList[] newArray(int size) {
return new ChildList[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String Title) {
this.title = Title;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
}
Please anyone help me with this :(
Don't use equalTo().
Try this:
DatabaseReference parentReference = database.getReference().child("Tutors");
parentReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot snapshot : dataSnapshot.getChildren()){
final String NameKey = snapshot.getKey().toString();
if(value.equals(NameKey)){
//DO WHATEVER YOU WANT
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to get data from Firebase and display it in a recyclerview? [duplicate]

This question already has answers here:
How to update RecyclerView Adapter Data
(16 answers)
Closed 3 years ago.
I develop a chat app. I try to get data from firebase database and display it in a recyclerview, but it doesn't work. I searched it on Google and I tried a lot of options, but it displays nothing. What am I doing wrong?
These are the activities:
1.Main Activity(Where I want to display the data)
public class SearchActivity extends AppCompatActivity {
Toolbar sToolbar;
SearchView searchView;
RecyclerView recyclerView;
BottomNavigationView sBnv;
SearchAdapter searchAdapter;
LinearLayoutManager llm;
ArrayList<String> arrayList;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
sToolbar = findViewById(R.id.sToolbar);
recyclerView = findViewById(R.id.sRecyclerView);
sBnv = findViewById(R.id.sBnv);
searchAdapter = new SearchAdapter(arrayList, getApplicationContext());
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(getApplicationContext());
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SearchActivity.this, "Database error", Toast.LENGTH_SHORT)
.show();
}
});
2.Adapter class:
public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {
ArrayList<String> friendsSearchedList = new ArrayList<>();
Context mContext;
public SearchAdapter(ArrayList<String> friendsSearchedList, Context mContext){
this.friendsSearchedList = friendsSearchedList;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_user_item,parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final String username = friendsSearchedList.get(position);
holder.text.setText(username);
}
#Override
public int getItemCount() {
return friendsSearchedList == null ? 0:friendsSearchedList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView text, text1, text2;
Button button;
RelativeLayout relativeLayout;
public ViewHolder(View itemView){
super(itemView);
text = itemView.findViewById(R.id.sText);
button = itemView.findViewById(R.id.addFriend);
text1 = itemView.findViewById(R.id.sText1);
text2 = itemView.findViewById(R.id.sText2);
relativeLayout = itemView.findViewById(R.id.relativeLayout);
}
}
}
3.User class:
public class User {
public String email, id, password;
public String username;
public User(String email, String username, String password){
this.email = email;
this.username = username;
this.password = password;
}
public User(){}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}
Initially the arraylist which your setting for the recyclerview is empty. When you are adding the data to that list you have to notify the recycler view adapter. So your code should look like this way:
searchAdapter = new SearchAdapter(arrayList, getApplicationContext());
// remove this line
/* recyclerView.setHasFixedSize(true);*/
llm = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
***searchAdapter.notifyDataSetChanged();***
}
}
If it’s a simple chat maybe a listview would be more convenient for you.
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
}
#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) {
}
});
This should easily do the trick…
Create a method in your SearchAdapter.class like below
public void addData(ArrayList<String> list){
this.mDataSet = list;
notifyDataSetChanged();
}
And once you receive data from Firebase database, update it to the adapter like below.You need to tell the recycler view that your data set has been updated.
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String username = (String)
snapshot.child("username").getValue();
arrayList.add(username);
}
recyclerView.setLayoutManager(llm);
recyclerView.setAdapter(searchAdapter);
searchAdapter.addData(arrayList); // Add this line
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(SearchActivity.this, "Database error", Toast.LENGTH_SHORT)
.show();
}
});

Firebase Database Child Count

I am developing an Android App which receives data from Firebase Realtime Database. Here is a Snapshot of my Database.
I want to get the number of children under the Comments field.
Here is my code:
public static class PostsViewHolder extends RecyclerView.ViewHolder
{
View mView;
ImageButton commentPostButton;
TextView DisplayNoOfInterest;
int countComments;
String currentUserId;
DatabaseReference CommentsRef;
public PostsViewHolder(View itemView)
{
super(itemView);
mView = itemView;
commentPostButton = (ImageButton)
mView.findViewById(R.id.commentPost);
DisplayNoOfInterest = (TextView) mView.findViewById(R.id.interest);
CommentsRef = FirebaseDatabase.getInstance().getReference();
currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setCommentStatus() {
CommentsRef.child("Posts").child("Comments").addValueEventListener(new ValueEventListener())
{
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
countComments = (int) dataSnapshot.getChildrenCount();
int cc = Integer.toString(countComments)
DisplayNoOfInterest.setText(cc);
}
}
}
}
Try this
FirebaseDatabase.getInstance().getReference().child("Posts").child(yourPostId).child("Comments").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
DisplayNoOfInterest.setText(""+dataSnapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I hope that can help you!
Thank You.
Your reference is wrong. You need to pass the postID before trying to get comments, because the comments node is under each postID.
After referencing the right node, then you can call : dataSnapshot.getChildrenCount()
Example:
CommentsRef.child("Posts").child(POSTID).child("Comments").addValueEventListener(new ValueEventListener()){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
countComments = (int) dataSnapshot.getChildrenCount();
}
DisplayNoOfInterest.setText(Integer.toString(countComments));
}
}

Android Firebase Failed to convert value of type java.util.HashMap to String

I'm trying to use the listview using array adapter on my fragment but when trying to do it using the tutorial, It crashes every time i open that specific fragment. I'm trying to show the data on my firebase into the listview but it crashes every time i open it.
Here's my database
From the picture My plan is to only show the email and name of the user and not to include the type but I'll do that later.
And here's my code
public class memberFragment extends Fragment {
private ListView mylistView;
private DatabaseReference mDatabase;
ArrayList<String> myArrayList = new ArrayList<>();
FirebaseDatabase myFirebase;
public memberFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_member2, container, false);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users");
final ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,myArrayList);
mylistView = (ListView)view.findViewById(R.id.listView);
mylistView.setAdapter(myArrayAdapter);
mDatabase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String myChildValues = dataSnapshot.getValue(String.class);
myArrayList.add(myChildValues);
myArrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
myArrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Inflate the layout for this fragment
return view;
Any ideas what might be causing the problem? I tried to searched and found out its related to hashmap or map, but I have no idea how to put it on my array?
The can use a model class in order to achieve this or you can use a simplest way, using the String class. For that, you can use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Accounts").child("Users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
Log.d("TAG", email + " / " + name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
a#b.com / idk
//and so on
If you want to get all values from reference data snapshot instead of dataSnapshot.getValue(String.class); you should create data class which contains these fields. As an example:
public class UserData {
private String name;
private String email;
private Integer type;
public UserData() {}
public UserData(String name, String email, Integer type) {
this.name = name;
this.email = email;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
Then using this class you can get all data of the user by using it like this:
UserData data = (UserData) dataSnapshot.getValue(UserData.class);.
And by using getters you can get the value you want.
The easier way would be to create an object for the list items you want to retrieve from Firebase and then use that object to set your list view items.
But if you are using simple list adapter then I suggest you make the following changes:
mDatabase.addValueEventListener(new ValueEventListener {
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String myChildValues = snapshot.getvalue(String.class);
myArrayList.add(myChildValues);
myArrayAdapter.notifyDataSetChange();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do this accordingly for each of your string data under "Users".

how to Retrieve data from firebase using firebase UI

Can anyone help me to retrieve data from every child except doctor_profile.
Do i need to create separate class for every child or there is another way to solve this problem.
TIA
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("addiction psychiatrist");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
Psychiatrist psychiatrist = snapshot.getValue(Psychiatrist.class);
//now you can add it to your list (collection) or do what you want
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and of course you must have class which represents your objects, so for example:
#IgnoreExtraProperties
public class Psychiatrist {
private String name;
private String city;
private String hospital;
public Psychiatrist() {
// required empty constructor
}
public Psychiatrist(String name, String city, String hospital) {
this.name = name;
this.city = city;
this.hospital = hospital;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
public String getHospital() {
return hospital;
}
}

Categories

Resources