I'm trying to make a comment system for posts on my social media app. In my database each post has a section inside of "comments" table, like so:
"hypno--######" is the title of the social media post. It Contains the comment, user id of the user who posted the comment, and a unixtimestamp when the comment was posted. Each comment is titled after the time it was posted.
This is the Comment class
public class comment {
public String uID;
public String comment_t;
public long unixTimestamp;
public comment() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public comment(String uID, String comment_t, long unixTimestamp) {
this.uID = uID;
this.comment_t = comment_t;
this.unixTimestamp = unixTimestamp;
}
public String getuID() {
return uID;
}
public void setuID(String uID) {
this.uID = uID;
}
public String getComment() {return comment_t;}
public void setComment() {this.comment_t = comment_t; }
public long getUnixTimestamp() {
return unixTimestamp;
}
}
This is the Comment Adapter:
Public class Adapter_Comment extends FirebaseRecyclerAdapter<comment, Adapter_Comment.ViewHolder_com> {
private DatabaseReference mDatabase;
private static final String TAG = "RecyclerViewAdapter";
private Context mContext;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private static AppCompatActivity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (AppCompatActivity) context;
}
public Adapter_Comment(#NonNull FirebaseRecyclerOptions<comment> options) {
super(options);
//this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder_com onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_comment, parent, false);
mDatabase = FirebaseDatabase.getInstance().getReference();
return new ViewHolder_com(view);
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder_com holder, int position, #NonNull comment model) {
mDatabase = FirebaseDatabase.getInstance().getReference();
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
holder.postPfp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//AppCompatActivity activity = (AppCompatActivity) v.getContext();
AppCompatActivity activity = unwrap(v.getContext());
Fragment OtherProfileFragment = new OtherProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("key", model.getuID());
OtherProfileFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, OtherProfileFragment).addToBackStack(null).commit();
}
});
}
public class ViewHolder_com extends RecyclerView.ViewHolder {
TextView comment_text;
CircleImageView postPfp;
TextView time;
RelativeLayout comment_layout;
public ViewHolder_com(#NonNull View itemView) {
super(itemView);
postPfp = itemView.findViewById(R.id.iv_comment_icon);
comment_text = itemView.findViewById(R.id.tv_comment_text);
time = itemView.findViewById(R.id.tv_comment_time);
comment_layout = itemView.findViewById(R.id.comment_layout);
}
}
}
This is Comment Fragment:
public class CommentFragment extends Fragment {
private DatabaseReference mDatabase;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
View view;
String value;
RecyclerView recyclerView;
Query query;
TextView comment_text;
long unixTime = System.currentTimeMillis() / 1000L;
public long globalUnix;
Button comment_post;
String comment_string;
Adapter_Comment adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_comment, container, false);
value = getArguments().getString("key");
mDatabase = FirebaseDatabase.getInstance().getReference();
recyclerView = view.findViewById(R.id.recyclerv_comment);
comment_text = view.findViewById(R.id.tv_comment_type);
comment_post = view.findViewById(R.id.btn_comment_post);
globalUnix = (unixTime * -1);
comment_post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(comment_text.getText().toString() == NULL){
Toast.makeText(getActivity(), "No Comment Typed", Toast.LENGTH_LONG).show();
}
else{
comment com = new comment();
com.uID = user.getUid();
com.comment_t = comment_text.getText().toString();
com.unixTimestamp = globalUnix;
mDatabase.child("comments").child(value).child(globalUnix + "").setValue(com);
}
}
});
initRecyclerView();
return view;
}
private void initRecyclerView(){
//Log.d(TAG, "initRecyclerView: init recyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
query = FirebaseDatabase.getInstance().getReference().child("comments").orderByValue();
FirebaseRecyclerOptions<comment> options = new FirebaseRecyclerOptions.Builder<comment>().setQuery(query, comment.class).build();
adapter = new Adapter_Comment(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
adapter.notifyDataSetChanged();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Inside of the adapter I'm using the comment model, to get the uID, comment and timestamp to fill the holder, however when i set these values im getting null values. Is there something im missing when trying to connect the adapter/firebase and model/holder?
long dv = model.getUnixTimestamp()*-1000;
Date df = new java.util.Date(dv);
String vv = new SimpleDateFormat("MM dd, yyyy hh:mma", Locale.ENGLISH).format(df);
holder.time.setText(vv);
String com = model.getComment();
holder.comment_text.setText(com);
mDatabase.child("users").child(model.getuID()).child("profileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists())
{
final String picUrl = snapshot.getValue(String.class);
Glide.with(holder.postPfp.getContext()).load(picUrl).into(holder.postPfp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) { }
});
There's really too much going on in here, but...
As far as I can see you're creating a FirebaseUI adapter on FirebaseDatabase.getInstance().getReference().child("comments"). FirebaseUI adapters show the direct child nodes of the node you pass in, so in your case it'll create one view for the hypno---...196 node. You're trying to read a Comment object from there, but don't exist until one level lower in your JSON.
So you can:
Either show the comments for one post, by basing the adapter off of that. So: FirebaseDatabase.getInstance().getReference().child("comments").child("hypno---...196") (which the real key in there).
Or you can show one piece of information about each post, for example its key.
If you want to show a flat list of comments for all posts through the FirebaseUI adapter, you'll have to store a flat list of comments across all posts in your database too.
Related
List all information of both service providers (Babysitter and Kids event planner) from the Account class
public class Register_Requests extends Fragment {
FirebaseAuth mAuth;
DatabaseReference refAccount,searchdatabase;
FirebaseUser user;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
RecyclerView recyclerView;
Adapter adapter;
TextView Fullname_Admin;
Button btnlogOutAdmin,search_bar;
String F_name, L_name;
ArrayList<Account> list = new ArrayList();
private String mParam1;
private String mParam2;
public Register_Requests() { }
public static Register_Requests newInstance(String param1, String param2) {
Register_Requests fragment = new Register_Requests();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);}}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_register__requests, container, false);
ImageView imgfake;
TextView nametext,SPtext,count;
imgfake=view.findViewById(R.id.imgfake);
nametext=view.findViewById(R.id.nametext);
SPtext=view.findViewById(R.id.SPtext);
count= (TextView) view.findViewById(R.id.counttext);
btnlogOutAdmin = view.findViewById(R.id.signout_admin);
Fullname_Admin= (TextView) view.findViewById(R.id.name_admin);
recyclerView =(RecyclerView)view.findViewById(R.id.recview_SP);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
user= FirebaseAuth.getInstance().getCurrentUser();
refAccount = FirebaseDatabase.getInstance().getReference().child("Account");
String Id_admin = FirebaseAuth.getInstance().getCurrentUser().getUid();
// Welcome admin
FirebaseDatabase.getInstance().getReference("Admin").child(Id_admin)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Admin admin_display = snapshot.getValue(Admin.class);
if(admin_display != null){
F_name = admin_display.getA_FullName();
L_name = admin_display.getA_LastName();
Fullname_Admin.setText("Welcome "+F_name+" "+L_name+" !");}}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getActivity(),"Something Wrong Happened",Toast.LENGTH_SHORT).show();}});
// Logout admin
btnlogOutAdmin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
perfrences.clearData(getActivity());
getActivity().finish();
startActivity(new Intent(getActivity(),Login.class));}});
// List Babysitter and Kids Event Planner from Account
refAccount.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
if (snapshot.exists())
{
for (DataSnapshot snapshot1: snapshot.getChildren())
{
Account a=snapshot1.getValue(Account.class);
list.add(a);
}
adapter.notifyDataSetChanged();
count.setText(adapter.getItemCount()+" Registers"); }
else
{ nametext.setText("No Available Service Providers");
nametext.setVisibility(View.VISIBLE);} }
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
// Adapter for recycle view
FirebaseRecyclerOptions<Account> options =
new FirebaseRecyclerOptions.Builder<Account>()
.setQuery(refAccount, Account.class)
.build();
adapter = new Adapter(options);
recyclerView.setAdapter(adapter);
adapter.startListening();
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}}
Adapter class where I'll get access from Account class to both service provider
public class Adapter extends FirebaseRecyclerAdapter<Account, Adapter.viewHolder> {
DatabaseReference Ref,Ref2,check;
boolean flag =true, flag2=true;
String userIDs,total_count,IDsitter,IDplanner;
public Adapter(#NonNull FirebaseRecyclerOptions<Account> options) { super(options); }
#Override
protected void onBindViewHolder(#NonNull viewHolder holder, int position, #NonNull Account model) {
Ref= FirebaseDatabase.getInstance().getReference("Babysitter");
Ref2= FirebaseDatabase.getInstance().getReference("Kids Event Planner");
userIDs = model.user_id;
// Print all the Babysitter
Ref.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
if(snapshot.hasChild("b_FirstName")){
String Fname = snapshot.child("b_FirstName").getValue().toString();
String Lname = snapshot.child("b_LastName").getValue().toString();
String photo = snapshot.child("b_Photo").getValue().toString();
String gender = snapshot.child("b_Gender").getValue().toString();
String nationality = snapshot.child("b_Nationality").getValue().toString();
String phone = snapshot.child("b_Phone").getValue().toString();
String B_date = snapshot.child("b_BirthDate").getValue().toString();
int Y_e = parseInt(snapshot.child("years_of_Experience").getValue().toString());
String exp= Integer.toString(Y_e);
String state= snapshot.child("registration_Status").getValue().toString();
String educate= snapshot.child("b_EducationLevel").getValue().toString();
holder.nametext.setText(Fname +" "+ Lname );
holder.SPtext.setText(model.getAccount_role());
Picasso.with(holder.imgfake.getContext()).load(photo).placeholder(R.drawable.ic_action_name).into(holder.imgfake);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity=(AppCompatActivity)view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, new eachInfo_SP(model.user_id,Fname,Lname,photo,
gender,nationality,phone,B_date,model.getAccount_email(),model.getAccount_role(), exp,state,educate)).addToBackStack(null).commit();}});}
else { flag=false;System.out.println("No values");} if (!(model.account_role.equals("Admin"))&& !(model.account_role.equals("Parent")) ){
// Log.e(String.valueOf(snapshot.getKey().equals(userIDs)), snapshot.getChildrenCount() + " Registers");
total_count = snapshot.getChildrenCount() + " Registers";
System.out.println(total_count);
}}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}});
// Print all the KEP
Ref2.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
KidsEventPlanner k= snapshot.getValue(KidsEventPlanner.class);
if(snapshot.hasChild("e_FirstName")){
String Fname = snapshot.child("e_FirstName").getValue().toString();
String Lname = snapshot.child("e_LastName").getValue().toString();
String photo = snapshot.child("e_Photo").getValue().toString();
String gender = snapshot.child("e_Gender").getValue().toString();
String nationality = snapshot.child("e_Nationality").getValue().toString();
String phone = snapshot.child("e_Phone").getValue().toString();
String B_date = snapshot.child("e_BirthDate").getValue().toString();
int Y_e = parseInt(snapshot.child("years_of_experience").getValue().toString());
String exp= Integer.toString(Y_e);
String state= snapshot.child("registration_status").getValue().toString();
String educate= snapshot.child("e_EducationLevel").getValue().toString();
holder.nametext.setText(Fname +" "+ Lname );
holder.SPtext.setText(model.getAccount_role());
Picasso.with(holder.imgfake.getContext()).load(photo).placeholder(R.drawable.ic_action_name).into(holder.imgfake);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity=(AppCompatActivity)view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, new eachInfo_SP(model.user_id,Fname,Lname,photo,
gender,nationality,phone,B_date,model.getAccount_email(),model.getAccount_role(), exp, state,educate)).addToBackStack(null).commit();}});}
else{flag2 = false; System.out.println("False");}} }
#Override
public void onCancelled(#NonNull DatabaseError error) {}});
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdata,parent,false);
viewHolder viewHolder = new viewHolder(view);
return viewHolder;}
public class viewHolder extends RecyclerView.ViewHolder
{
ImageView imgfake;
TextView nametext,SPtext,count;
public viewHolder(#NonNull View itemView) {
super(itemView);
imgfake=itemView.findViewById(R.id.imgfake);
nametext=itemView.findViewById(R.id.nametext);
SPtext=itemView.findViewById(R.id.SPtext);
count= (TextView) itemView.findViewById(R.id.counttext);}}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
This is the Account class where I'll save the user's ID. Basically, I have in this class 4 users and just wanted related information of service providers
public class Account {
String account_email,account_password ,account_role, user_id;
public Account() {}
public Account(String account_email, String account_password, String account_role, String user_id) {
this.account_email = account_email;
this.account_password = account_password;
this.account_role = account_role;
this.user_id = user_id;
}
public String getAccount_email() {return account_email;}
public void setAccount_email(String account_email) {this.account_email = account_email;}
public String getAccount_password() {return account_password;}
public void setAccount_password(String account_password) {this.account_password = account_password; }
public String getAccount_role() {return account_role;}
public void setAccount_role(String account_role) {this.account_role = account_role; }
public String getUser_id() { return user_id; }
public void setUser_id(String user_id) { this.user_id = user_id;}
}
As you can see in the account_role these are 3 users and the 4th is the parent
there are 16 nodes in the Account path
those are other paths of (Service providers) which is in total 8 nodes
The problem is I just invoked only the service provider's information which should display 8 items in recycle view but here is displaying the rest of the items in the account class which in total 16 items, which means 8 item's data is shown but the rest is empty and I want to display item list as the size of service providers. So How I can prevent this problem?
It's showing empty rows from the Account class.
To get only the child nodes from under /Account with a specific value for account_role, you can use a query to order and filter data:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Account");
Query query = ref.orderByChild("account_role").equalTo("Babysitter");
query. addListenerForSingleValueEvent(...
But you can only do this for a single value (like Babysitter above), or for a contiguous range of values (like: from Admin to Babysitter). There is no way to request (with a single query) a number of distinct values like you want.
Some options:
Perform a query (like I showed above) for each value, and then merge the results in your client-side code. The performance of this will be fine, but it will be a bit more code.
Give each child node a single property that exactly matches your condition, so for example: "Babysitter_or_KidsEventPlanner": true. Then you can filter on that property. This works best if you have a limited number of such combinations.
Perform a query on a range of values, for example: ref.orderByChild("account_role").startAt("Babysitter").endAt("Kids Event Planner"). Just keep in mind that this returns all nodes where the account_role value is between Babysitter and Kids Event Planner, so it'd also include nodes with Car mechanic. Sometimes this is a good option though, especially if you can order/rename the values in a way to allow your query needs.
Please see the following issue:
All User Profile Images are not successfully displaying in the RecyclerView.
Text view is successfully displaying in the RecyclerView.
I looked up other similar issues online, but have not been able to find a solution.
I have updated my google play services, and my Firebase storage dependencies.
I am able to successfully pull the current user profile image in another activity.
I am getting the following 404 error message below:
**Adapter**
public class FindFriendsAdapter extends RecyclerView.Adapter<FindFriendsAdapter.FindFriendsViewHolder>
{
private Context context;
private List<FindFriendModel> findFriendModelList;
////This is a constructor and is a must have for recyclerviews/////
public FindFriendsAdapter(Context context, List<FindFriendModel> findFriendModelList) {
this.context = context;
this.findFriendModelList = findFriendModelList;
}
////This is a constructor and is a must have for recyclerviews/////
#NonNull
#Override
public FindFriendsAdapter.FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.find_friends_layout, parent, false);
return new FindFriendsViewHolder(view); ///// layout converts our xml layout file to a programmable file some kind of way.
}
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
StorageReference fileref = FirebaseStorage.getInstance().getReference().child(Constants.IMAGES_FOLDER +"/" + friendModel.getProfileimage());
fileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(context)
.load(uri)
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
});
}
#Override
public int getItemCount() {
return findFriendModelList.size();
}
public class FindFriendsViewHolder extends RecyclerView.ViewHolder{
private CircleImageView imageView_profile;
private TextView text_view_full_name;
private ImageButton button_request, button_cancel_request;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
imageView_profile = itemView.findViewById(R.id.find_friends_profile_picture);
text_view_full_name = itemView.findViewById(R.id.find_friends_user_full_name);
button_request = itemView.findViewById(R.id.button_send_requests);
button_cancel_request = itemView.findViewById(R.id.button_cancel_requests);
}
}
}
**Model Class**
public class FindFriendModel
{
private String full_name;
private String profileimage;
private String userID;
private boolean requestSent;
public FindFriendModel(String full_name, String profileimage, String userID, boolean requestSent) {
this.full_name= full_name;
this.profileimage = profileimage;
this.userID = userID;
this.requestSent = requestSent;
}
public FindFriendModel() {}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public boolean isRequestSent() {
return requestSent;
}
public void setRequestSent(boolean requestSent) {
this.requestSent = requestSent;
}
}
**Fragment Java Class**
public class FindFriendsFragment extends Fragment {
private RecyclerView recycler_view_find_friends;
private FindFriendsAdapter findFriendsAdapter;
private List<FindFriendModel> findFriendModelList;
private TextView text_view_empty_Friends_List;
private DatabaseReference databaseReference;
private FirebaseUser currentUser;
public FindFriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_find_friends, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recycler_view_find_friends = view.findViewById(R.id.recycler_view_find_friends);
text_view_empty_Friends_List = view.findViewById(R.id.text_view_empty_find_friends);
recycler_view_find_friends.setLayoutManager(new LinearLayoutManager(getActivity()));
findFriendModelList = new ArrayList<>();
findFriendsAdapter = new FindFriendsAdapter(getActivity(), findFriendModelList);
recycler_view_find_friends.setAdapter(findFriendsAdapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
text_view_empty_Friends_List.setVisibility(View.VISIBLE);
Query query = databaseReference.orderByChild("full_name");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
findFriendModelList.clear();
for (final DataSnapshot ds : dataSnapshot.getChildren())
{
final String userID = ds.getKey();
if (userID.equals(currentUser.getUid()))
return;
if (ds.child("full_name").getValue()!=null)
{
String fullName = ds.child("full_name").getValue().toString();
String profileImage = ds.child("profileimage").getValue().toString();
findFriendModelList.add(new FindFriendModel(fullName, profileImage, userID, false));
findFriendsAdapter.notifyDataSetChanged();
text_view_empty_Friends_List.setVisibility(View.GONE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(),"Failed to fetch friends", Toast.LENGTH_SHORT).show();
}
});
}
}
````
ds.child("full_name").getValue()!=null should be replaced by
Objects.equals(ds.child("full_name"), null)
It worked for me when I had the same error, maybe it will help you as well !
Figured out the issue:
The issue was that I was already saving my images images to Firebase Storage, and I was trying to get the download url string again.
I fixed the following part of my adapter:
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
Glide.with(context)
.load(friendModel.getProfileimage())
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
Can anyone help me here I am confused as I have tried many example but I am getting always getting it wrong I guess firebase is not beginners friendly, what I am trying to achieve is getting a profile image from my table called Users and fetch the profile image using Glide or Picasso, inside this users table I have Username, Password, email, profilePic, userIds, my profile image url is saved on profilePic child table on User registration, I have tried some code but it is giving a null. Here is what I have tried.
String url = dataSnapshot.child(Common.currentUser.getUserName() +"/"+ "profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
This worked on fetching image but its only showing profile images on currentUserr so all image holder have same image, also I have tried this first which is fetching the url manually.
String url="https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";//Retrieved url as mentioned above
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
and also with this code
String url = dataSnapshot.child(users.child("/")+ "/profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
I am getting the path is correct I gess but still getting error like this
Invalid Firebase Database path: https://learnbravanese.firebaseio.com/Users/mo/profilePic. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
can someone help me please how to get each image for its user and show it on this fragment?
here is my full fragment.
public class RankingFragment extends Fragment {
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl,imageTable;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
DataSnapshot dataSnapshot;
private Context context;
String Storage_Path = "All_Image_Uploads/";
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
private FirebaseAuth mAuth;
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
imageTable = database.getReference("DefaultImages");
storageReference = FirebaseStorage.getInstance().getReference("All_Image_Uploads/");
users = FirebaseDatabase.getInstance().getReference("Users");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
// storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference().child("Users");
final String pathtobackimage;
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(final RankingViewHolder viewHolder, final Ranking model, int position) {
// StorageReference backref = storageReference.child("All_Image_Uploads/1584768076891.jpg");
// FirebaseUser firebaseUser = mAuth.getCurrentUser();
ImageView imageView;
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
// String url = "https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";
;
//users = FirebaseDatabase.getInstance().getReference().child("Users").child(model.getUserName());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//String imageUrl = dataSnapshot.child("profilePic").getValue().toString();
String url = dataSnapshot.child(Common.currentUser.getUserName() +"/"+ "profilePic").getValue().toString();
// String url="https://firebasestorage.googleapis.com/v0/b/learnbravanese.appspot.com/o/images%2Fmoh2%2Fmoh2back?alt=media&token=d97130a4-c6ac-409f-a0ad-71fdcdea1e97";//Retrieved url as mentioned above
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
// String link =dataSnapshot.child("profilePic").getValue().toString();
Picasso.with(getContext()).load(url).into(viewHolder.profileImageView);
// Picasso.with(getContext()).load(dataSnapshot.child("profilePic").getValue(User_Info.class).toString())
// .into(viewHolder.profileImageView);
// Glide.with(getContext()).load(users.child(model.getUserName() +"/"+ "profilePic"))
// .into(viewHolder.profileImageView);
// Glide.with(getContext()).load(model.getImage()).into(viewHolder.profileImageView);
// Glide.with(getContext()).load(model.getUrlProfilePic())
// .into(viewHolder.profileImageView);
// Glide.with(viewHolder.profileImageView.getContext()).load(model.getProfilepic()).into(viewHolder.profileImageView);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum,userName,userName);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
After few tries I have managed to fix the null issue by trying this code, I was calling for a wrong Firebase table I am guessing.
#Override
protected void populateViewHolder(final RankingViewHolder viewHolder, final Ranking model, int position) {
ImageView imageView;
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.with(getActivity()).load(dataSnapshot.child(model.getUserName()).child("profilePic").getValue().toString())
.into(viewHolder.profileImageView);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
I am only learning so I have no idea what else was wrong.
For months I have created a chat for the Android system using Firebase as a database.
I followed this guide here
( link ) and at the beginning it was all right, the chat was good and it didn't have any kind of delays. I then started to add other particularities, such as the display or not of the message and the status of the participants (online and offline) and from that moment three problems began to manifest in particular:
1) when I change the chat activity to go to another and then return to the chat, the layout appears empty without messages and if you try to change the activity the application closes itself. I found out that I get this error:
E/RecyclerView: No adapter attached; skipping layout
These are the files that make up the part related to chat:
MessageChat.java
public class MessageChat {
private String sender;
private String receiver;
private String msg;
private String currenttime;
private boolean isseen;
public MessageChat(String sender, String receiver, String msg, String currenttime, boolean isseen){
this.sender = sender;
this.receiver = receiver;
this.msg = msg;
this.currenttime = currenttime;
this.isseen = isseen;
}
public MessageChat(){}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {return receiver;}
public void setReceiver(String receiver) { this.receiver = receiver;}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCurrenttime() {
return currenttime;
}
public void setCurrenttime(String currenttime) {
this.currenttime = currenttime;
}
public boolean isIsseen() {return isseen;}
public void setIsseen(boolean isseen) {this.isseen = isseen;}
}
msgAdapter.java
public class msgAdapter extends RecyclerView.Adapter<msgAdapter.MsgViewHolder> {
public static final int INT_TYPE_LEFT = 0;
public static final int INT_TYPE_RIGHT = 1;
private static List<MessageChat> mChat;
private static Context context;
private FirebaseUser fuser;
public msgAdapter(List<MessageChat> msg, Context context) {
this.mChat = msg;
this.context = context;
}
#Override
public msgAdapter.MsgViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == INT_TYPE_RIGHT) {
View view = LayoutInflater.from(context).inflate(R.layout.right_message, null);
msgAdapter.MsgViewHolder msgViewHolder = new msgAdapter.MsgViewHolder(view);
return msgViewHolder;
}else{
View view = LayoutInflater.from(context).inflate(R.layout.left_message, null);
msgAdapter.MsgViewHolder msgViewHolder = new msgAdapter.MsgViewHolder(view);
return msgViewHolder;
}
}
#Override
public void onBindViewHolder(final msgAdapter.MsgViewHolder holder, final int position) {
MessageChat msg = mChat.get(position);
holder.show_msg.setText(msg.getMsg());
if ((position == mChat.size()-1) && msg.getSender().equals(fuser.getUid())){
if (msg.isIsseen()){
holder.tv_seen.setText(" Seen ");
holder.tv_seen.setVisibility(View.VISIBLE);
}else {
holder.tv_seen.setText(" Sent ");
holder.tv_seen.setVisibility(View.VISIBLE);
}
}else{
holder.tv_seen.setVisibility(View.GONE);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public static class MsgViewHolder extends RecyclerView.ViewHolder {
TextView username, show_msg, tv_seen;
public MsgViewHolder(final View itemView) {
super(itemView);
show_msg = (TextView) itemView.findViewById(R.id.show_msg);
tv_seen = (TextView) itemView.findViewById(R.id.tv_seen);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// item clicked
MessageChat msg = mChat.get(getAdapterPosition());
String ctime = msg.getCurrenttime();
TastyToast.makeText(context, ctime, TastyToast.LENGTH_LONG, TastyToast.INFO);
}
});
}
}
#Override
public int getItemViewType(int position) {
fuser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(fuser.getUid())){
return INT_TYPE_RIGHT;
}else{
return INT_TYPE_LEFT;
}
}
}
On the internet I have found many answers that solve this problem in the following way, replacing this:
View view = LayoutInflater.from(context).inflate(R.layout.right_message, null);
to this:
View view = LayoutInflater.from(context).inflate(R.layout.right_message, parent, false);
But in my case I only got the busted chat with empty spaces between one comic and another.
Homefragment.java
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private View v;
private ImageButton btn_send;
private EditText et_send_mex;
private DatabaseReference reference;
private msgAdapter mAdapter;
private List<MessageChat> mChat;
private RecyclerView recyclerView;
private FirebaseUser user;
private String Uid, Oid;
private static final String sId = "xyz1";
private static final String pId = "xyz2";
ValueEventListener seenListener;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_home, container, false);
btn_send = v.findViewById(R.id.btn_send);
et_send_mex = v.findViewById(R.id.et_send_mex);
recyclerView = v.findViewById(R.id.rv_mex);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llManager = new LinearLayoutManager(getContext());
llManager.setStackFromEnd(true);
recyclerView.setLayoutManager(llManager);
user = FirebaseAuth.getInstance().getCurrentUser();
Uid = user.getUid();
btn_send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// notify = true;
String m = et_send_mex.getText().toString();
if (!m.equals("") || !m.equals("\n")){
if (Uid.equals(pId)){
sendMessage(Uid,sId,m);
}else if (Uid.equals(sId)){
sendMessage(Uid,pId,m);
}
}
}
});
readMessage();
return v;
}
private void seenMessage(final String senderId){
reference = FirebaseDatabase.getInstance().getReference("chats");
seenListener = reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
MessageChat msgchat = snapshot.getValue(MessageChat.class);
if (msgchat.getReceiver().equals(user.getUid()) && msgchat.getSender().equals(senderId)){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("isseen", true);
snapshot.getRef().updateChildren(hashMap);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String sender, String receiver, String message){
reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
month = month+1;
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int sec = c.get(Calendar.MINUTE);
String dt = day+" - "+month+" - "+year+", "+hour+":"+sec;
hashMap.put("currenttime", dt);
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("msg", message);
hashMap.put("isseen", false);
reference.child("chats").push().setValue(hashMap);
et_send_mex.setText("");
}
private void readMessage (){
mChat = new ArrayList<>();
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mChat.clear();
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
MessageChat chat = snapshot.getValue(MessageChat.class);
mChat.add(chat);
if (!chat.getSender().equals(Uid)){
Oid = chat.getSender();
seenMessage(Oid);
}
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// user status
private void status(String status){
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(user.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
month = month+1;
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int sec = c.get(Calendar.MINUTE);
String dt = day+" - "+month+" - "+year+", "+hour+":"+sec;
hashMap.put("lastaccess", dt);
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
public void onResume() {
super.onResume();
status("online");
recyclerView.setAdapter(mAdapter);
}
#Override
public void onPause() {
super.onPause();
reference.removeEventListener(seenListener);
status("offline");
}
}
I was also advised to add in here:
#Override
public void onResume() {
super.onResume();
status("online");
}
The following code:
recyclerView.setAdapter(mAdapter);
But with poor results (maybe you can suggest me if it is right to add this part here or not, thank you very much)
2) When I send a message, it often takes a long time to reach the database, let's say that Firebase is not really a realtime database. Here I have not encountered any type of error, it is simply very slow.
3) Later I also added the change of state, simply when the application is closed or in background ( onPause () ), the state is set to offline in the database, otherwise it is online. But often it doesn't work properly, probably application crashes or delays affect this.
I remain available for any other part of the code or for clarification.
I thank you in advance for your help and I apologize for my bad English, I have been working on this application since last spring and I still have not been able to solve these problems.
first thing you want to do is, remove the part in your onCreate.
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
readMessage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here you basically put a reference on the database (chats) and every time it changes, it will call your function readMessage, which will always override your messages and put another listener on the same spot. Make sure you understand, that addValueEventListener is triggered every time the tree/path (chats) in firebase is updated!
You could simply replace the code from above with:
readMessage();
that would already make sure it is listening to your db. I believe that firebase is not slow, but that the two listeners maybe overriding their result.
About the next part i am not 100%, but i believe you can remove
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
from onDataChange (in readMessage) and put it directly under that part where you create the ArrayList. Like this:
mChat = new ArrayList<>();
mAdapter = new msgAdapter(mChat,getContext());
recyclerView.setAdapter(mAdapter);
reference = FirebaseDatabase.getInstance().getReference("chats");
I hope i understood your problem and my answer will give you a bit more clarity :)
Greetings!
Code
public class HomeScreen_Friends extends Fragment {
private View rootView;
private String userName;
private String UID;
private TextView noUsersText;
private ProgressDialog mProgressDialogue;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabaseReference;
private DatabaseReference mUsersDatabase;
private RecyclerView mUsersList;
private FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_friends, container, false);
noUsersText = (TextView) rootView.findViewById(R.id.noUsersText);
mUsersList = (RecyclerView) rootView.findViewById(R.id.usersList);
mUsersList.addItemDecoration(new DividerItemDecoration(getContext(),
DividerItemDecoration.HORIZONTAL));
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
UID = mAuth.getCurrentUser().getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Friends").child(UID);
mDatabaseReference.keepSynced(true);
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("UserData");
mUsersDatabase.keepSynced(true);
mProgressDialogue = new ProgressDialog(getActivity());
mProgressDialogue.setMessage("Loading...");
mProgressDialogue.show();
mUsersList.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerOptions<AllUsersHelper> options =
new FirebaseRecyclerOptions.Builder<AllUsersHelper>()
.setQuery(mDatabaseReference, AllUsersHelper.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllUsersHelper, UsersViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final UsersViewHolder holder, int position, #NonNull AllUsersHelper model) {
holder.setName(model.getName());
holder.setStatus(model.getStatus());
holder.setImage(model.getImage());
final String userId = getRef(position).getKey();
mUsersDatabase.orderByChild("Name");
mUsersDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mName = dataSnapshot.child("Name").getValue().toString();
String mStatus = dataSnapshot.child("Status").getValue().toString();
String mDisplayImage = dataSnapshot.child("Image").getValue().toString();
if(dataSnapshot.hasChild("Online")) {
String userOnline = dataSnapshot.child("Online").getValue().toString();
holder.setUserOnline(userOnline);
}
holder.setName(mName);
holder.setImage(mDisplayImage);
holder.setStatus(mStatus);
mProgressDialogue.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("UserData").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("Name").getValue().toString();
Intent intent = new Intent(getActivity(), Chat.class);
intent.putExtra("Recievers_Id", userId);
intent.putExtra("Recievers_Name", userName);
startActivity(intent);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_activity_all_users, parent, false);
return new UsersViewHolder(view);
}
};
mUsersList.setAdapter(firebaseRecyclerAdapter);
return rootView;
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
public View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name) {
TextView mDisplayName = (TextView) mView.findViewById(R.id.display_name);
mDisplayName.setText(name);
}
public void setStatus(String status) {
TextView mDisplayStatus = (TextView) mView.findViewById(R.id.display_status);
mDisplayStatus.setText(status);
}
public void setImage(String image) {
CircularImageView mDisplayImage = (CircularImageView) mView.findViewById(R.id.circleImageView);
Picasso.get().load(image).into(mDisplayImage);
}
public void setUserOnline(String userOnline) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.online);
if(userOnline.equals("Online")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
#Override
public void onStart() {
super.onStart();
firebaseRecyclerAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
if(firebaseRecyclerAdapter != null) {
firebaseRecyclerAdapter.stopListening();
}
}
}
Where should i put the keepSynced method for retrieving data offline because i tried below the database reference and it still doesn't show my data when i have no internet. Can someone help me out please... Also if the resukt is null how can i stop the progress dialog and show a text which says there are no users.
Right now you're just telling Firebase to keep an empty listener active on your Friends and UserData nodes. This ensures that the data from these nodes is always kept up to date (even when you don't attach any other listeners), but the data is still only kept in memory.
To persist the memory cache to disk, so that it can be reloaded in case you don't have an internet connection when starting the app, you'll need to call FirebaseDatabase.getInstance().setPersistenceEnabled(true) when the app starts. See enabling disk persistence in the Firebase docs.
Also see:
Firebase : What is the difference between setPersistenceEnabled and keepSynced?