Fragment not displaying more than one item using firebase - java

I have created an Android chat application which incorporates Firebase and created a fragment with a current users messages. The error occurs when a user sends a message to more than one person and the following image link shows how the first user is displayed whereas the most recent one who I have sent a message to is invisible. Does anyone know why this would be? I will include a few of my classes below.
My firebase is displayed as the following with messages containing first the user IDs, recipient IDs and then the unique message ID followed by the actual message and who sent it.
Thanks for your help.
https://i.stack.imgur.com/TrFUg.png
https://i.stack.imgur.com/M5LXa.png
Fragment Class
public class ChatFragment extends Fragment {
private RecyclerView convList;
private FirebaseAuth auth;
private DatabaseReference userDatabase, messageDatabase;
private View view;
public ChatFragment() {
// Required empty public constructor
}
// Chat Fragment initialised
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_chat, container, false);
convList = (RecyclerView) view.findViewById(R.id.conv_list);
convList.setHasFixedSize(true);
convList.setLayoutManager(new LinearLayoutManager(getContext()));
auth = FirebaseAuth.getInstance();
String currentUser;
currentUser = auth.getCurrentUser().getUid();
messageDatabase = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUser);
messageDatabase.keepSynced(true);
userDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
userDatabase.keepSynced(true);
return view;
}
// Use FirebaseRecyclerAdapter to populate each user of which messages have been sent between, the latest message sent between each user displayed, ordering the list by most recent message and the user's online status
#Override
public void onStart() {
super.onStart();
Query conversationQuery = messageDatabase.orderByChild("time");
FirebaseRecyclerAdapter<UserConversation, ConvViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<UserConversation, ConvViewHolder>(
UserConversation.class,
R.layout.activity_user_list,
ConvViewHolder.class,
conversationQuery
) {
#Override
protected void populateViewHolder(final ConvViewHolder friendsViewHolder, final UserConversation friends, int i) {
final String user_id = getRef(i).getKey();
Query lastMessageQuery = messageDatabase.child(user_id).limitToLast(1);
// Retrieving data stored in Firebase for each message and its information
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("message").getValue().toString();
ConvViewHolder.setMessage(data);
String time = dataSnapshot.child("time").getValue().toString();
ConvViewHolder.setTime(time);
}
#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) {
}
});
userDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
String online = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserOnline(online);
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), Messenger.class);
intent.putExtra("user_id", user_id);
intent.putExtra("user_name", userName);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.i("Activity Not Found", "Error");
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
convList.setAdapter(friendsRecyclerViewAdapter);
}
public static class ConvViewHolder extends RecyclerView.ViewHolder {
static View mView;
public ConvViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public static void setMessage(String message){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(message);
}
public void setName(String name) {
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx) {
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public static void setTime (String time){
TextView test = (TextView) mView.findViewById(R.id.time_sent);
test.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", Long.parseLong(time)));
}
public void setUserOnline(String online) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}

Related

How to remove values from Firebase when item is selected in recyclerview?

My app is displaying user's classes in a recylerview. When a user selects a specific class, it opens up another activity that displays the details and there is a button where a user can remove the class. When that button is clicked, i want the id of the class that is saved under the user's list of classes to be removed. I also want the user's uid to be removed from the list of students under the class.Also, I accidentally saved my class id as variable name uid, which shouldn't be confused with the user's uid.Let me know if you have any questions!
Here is my database structure:
{
"Classes" : {
"-LiGRe3e1YF_HFrHKMgi" : {
"Students" : {
"-LiId4URjJ8SWLAP4f4i" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22",
"-LiIeT5t1T7JpcUee_MJ" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22"
},
"class_info" : {
"date_clasname" : "mm",
"room_number" : "jjhh",
"subject" : "Science",
"teacher" : "mm",
"uid" : "-LiGRe3e1YF_HFrHKMgi"
}
}
},
"Users" : {
"UhTQgJ4jugMqFtEZK8CsIkTqQl22" : {
"Classes" : {
"-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
"-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
},
"User_info" : {
"email" : "samuelford48#gmail.com",
"grade" : "12",
"name" : "Samuel"
}
}
}
}
Here is the code of my activity that shows the classes and gets the data from Firebase:
public class home_fragment extends Fragment implements View.OnClickListener {
private Button button;
//DatabaseReference dref;
//ListView listview2;
//ArrayList<String> list=new ArrayList<>();
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
public home_fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home_fragment, container, false);
//FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
//if(fbUser == null) { Intent intent = new Intent(getContext(), LoginActivity.class);
// startActivity(intent);}
button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(this);
recyclerview = (RecyclerView) view.findViewById(R.id.rview);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
list = new ArrayList<>();
final adapter_user_remove_class recycler = new adapter_user_remove_class(list);
// final RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
//String postkey2 = dataSnapshot.getKey();
String class_id = dataSnapshot.getValue(String.class);
myRef = database.getReference("Classes").child(class_id).child("class_info");
// StringBuffer stringbuffer = new StringBuffer();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
Class_model new_class = dataSnapshot.getValue(Class_model.class);
assert new_class != null;
String nameofclass = new_class.getDate_clasname();
String teacherofclass = new_class.getTeacher();
String roomnumberofclass = new_class.getRoom_number();
String class_key = new_class.getUid();
Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
//String name = userdetails.getName();
//String email = userdetails.getEmail();
//String address = userdetails.getAddress();
listdata.setDate_class(nameofclass);
listdata.setTeacher(teacherofclass);
listdata.setRnumber(roomnumberofclass);
// recycler.notifyDataSetChanged();
list.add(listdata);
recycler.notifyDataSetChanged();
//recycler.notifyDataSetChanged();// Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
recyclerview.setLayoutManager(layoutmanager);
recyclerview.setItemAnimator(new DefaultItemAnimator());
recyclerview.setAdapter(recycler);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(DatabaseError error) {
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev#vigoschools.org!");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
return view;
}
Here is the code for my recycler adapter:
public class adapter_user_remove_class extends RecyclerView.Adapter<adapter_user_remove_class.MyHolder>{
List<Listdata> listdata;
public adapter_user_remove_class(List<Listdata> listdata) {
this.listdata = listdata;
}
#Override
public adapter_user_remove_class.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);
adapter_user_remove_class.MyHolder myHolder = new adapter_user_remove_class.MyHolder(view);
return myHolder;
}
public void onBindViewHolder(adapter_user_remove_class.MyHolder holder, final int position) {
final Listdata data = listdata.get(position);
holder.vdate_class.setText(data.getDate_class());
holder.vteacher.setText(data.getTeacher());
holder.vrnumber.setText(data.getRnumber());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( final View view) {
Context context = view.getContext();
Intent intent = new Intent(context, user_remove_class.class);
intent.putExtra("date_class", listdata.get(position).getDate_class());
intent.putExtra("teacher", listdata.get(position).getTeacher());
intent.putExtra("room_number", listdata.get(position).getRnumber());
intent.putExtra("post_key", listdata.get(position).getUid());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return listdata.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView vdate_class , vteacher,vrnumber;
public MyHolder(View itemView) {
super(itemView);
vdate_class = (TextView) itemView.findViewById(R.id.date_class_name);
vteacher = (TextView) itemView.findViewById(R.id.teacher);
vrnumber = (TextView) itemView.findViewById(R.id.room_number);
}
}
}
Here is the code for the activity that shows the details and handles the removal of data from Firebase:
public class user_remove_class extends AppCompatActivity {
private Button remove_class;
private FirebaseDatabase database;
private DatabaseReference myRef, myRef2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_remove_class);
final String date_class2 = getIntent().getStringExtra("date_class");
final String teacher = getIntent().getStringExtra("teacher");
final String room_number = getIntent().getStringExtra("room_number");
final String post_key = getIntent().getStringExtra("post_key");
TextView display_class_name = (TextView) findViewById(R.id.date_tv);
display_class_name.setText(date_class2);
TextView display_teacher = (TextView) findViewById(R.id.teacher_tv);
display_teacher.setText(teacher);
TextView display_room_number = (TextView) findViewById(R.id.rn_tv);
display_room_number.setText(room_number);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
remove_class = (Button) findViewById(R.id.add_class_2);
// final Query query = myRef.orderByChild("classes").equalTo(post_key);
//System.out.println(query);
remove_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
}
});
}
}
You can remove it by :
remove_class.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myRef = database.getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes").child(post_key);
myRef.removeValue();
}
});
You can Retrieve the Random key by this method .
MyRef.orderByChild("email").equalTo("blabla#blabla.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
}
}
Note that you have to pass the email by putExtra method and then match it with equalTo(); method . If email is exits in the random key it will retrive the ramdom key simple . :)
Hope it will work. If it works don't forget to Accept the question.

Fragment not displaying more than one item Firebase

I have created an Android chat application which incorporates Firebase and created a fragment with a current users messages. The error occurs when a user sends a message to more than one person and the following image link shows how the first user is displayed whereas the most recent one who I have sent a message to is invisible. Does anyone know why this would be? I will include a few of my classes below.
My firebase is displayed as the following with messages containing first the user IDs, recipient IDs and then the unique message ID followed by the actual message and who sent it.
Thanks for your help.
https://i.stack.imgur.com/TrFUg.png
Here on the link below you will see two tabs, the first is not displaying and the second is. Both messages are to different recipients.
https://i.stack.imgur.com/M5LXa.png
Fragment Class
public class ChatFragment extends Fragment {
private RecyclerView convList;
private FirebaseAuth auth;
private DatabaseReference userDatabase, messageDatabase;
private View view;
public ChatFragment() {
// Required empty public constructor
}
// Chat Fragment initialised
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_chat, container, false);
convList = (RecyclerView) view.findViewById(R.id.conv_list);
convList.setHasFixedSize(true);
convList.setLayoutManager(new LinearLayoutManager(getContext()));
auth = FirebaseAuth.getInstance();
String currentUser;
currentUser = auth.getCurrentUser().getUid();
messageDatabase = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUser);
messageDatabase.keepSynced(true);
userDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
userDatabase.keepSynced(true);
return view;
}
// Use FirebaseRecyclerAdapter to populate each user of which messages have been sent between, the latest message sent between each user displayed, ordering the list by most recent message and the user's online status
#Override
public void onStart() {
super.onStart();
Query conversationQuery = messageDatabase.orderByChild("time");
FirebaseRecyclerAdapter<UserConversation, ConvViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<UserConversation, ConvViewHolder>(
UserConversation.class,
R.layout.activity_user_list,
ConvViewHolder.class,
conversationQuery
) {
#Override
protected void populateViewHolder(final ConvViewHolder friendsViewHolder, final UserConversation friends, int i) {
final String user_id = getRef(i).getKey();
Query lastMessageQuery = messageDatabase.child(user_id).limitToLast(1);
// Retrieving data stored in Firebase for each message and its information
lastMessageQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String data = dataSnapshot.child("message").getValue().toString();
ConvViewHolder.setMessage(data);
String time = dataSnapshot.child("time").getValue().toString();
ConvViewHolder.setTime(time);
}
#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) {
}
});
userDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String userThumb = dataSnapshot.child("thumb_image").getValue().toString();
String online = dataSnapshot.child("online").getValue().toString();
friendsViewHolder.setName(userName);
friendsViewHolder.setUserImage(userThumb, getContext());
friendsViewHolder.setUserOnline(online);
friendsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), Messenger.class);
intent.putExtra("user_id", user_id);
intent.putExtra("user_name", userName);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.i("Activity Not Found", "Error");
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
convList.setAdapter(friendsRecyclerViewAdapter);
}
public static class ConvViewHolder extends RecyclerView.ViewHolder {
static View mView;
public ConvViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public static void setMessage(String message){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(message);
}
public void setName(String name) {
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setUserImage(String thumb_image, Context ctx) {
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.with(ctx).load(thumb_image).placeholder(R.drawable.default_avatar).into(userImageView);
}
public static void setTime (String time){
TextView test = (TextView) mView.findViewById(R.id.time_sent);
test.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", Long.parseLong(time)));
}
public void setUserOnline(String online) {
ImageView userOnlineView = (ImageView) mView.findViewById(R.id.user_single_online_icon);
if(online.equals("true")){
userOnlineView.setVisibility(View.VISIBLE);
} else {
userOnlineView.setVisibility(View.INVISIBLE);
}
}
}
}

Retrieve users followers list

I am trying to retrieve users followers from Firebase and populate them onto a RecyclerView for anyone to be able to see just like twitter and Instagram, when i run the app it returns an error.
My code:
public class ViewFollowersFragment extends Fragment {
private static final String TAG = "ViewFollowersFragment";
private CircleImageView myprofileimage;
private TextView username;
private ImageView arrow;
private ListView vfollowerslistview;
private DatabaseReference viewFollowersref,viewUserRef;
private FirebaseAuth mAuth;
private FirebaseListAdapter viewfollowersadapter;
private List<User> mUserList;
private User mUser;
String userid;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_followers, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
vfollowerslistview = (ListView) view.findViewById(R.id.viewfollowerslistview);
arrow = (ImageView) view.findViewById(R.id.fragfollowersbackarrow);
arrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().popBackStack();
getActivity().finish();
}
});
mUserList = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
userid = mAuth.getUid();
viewFollowersref = FirebaseDatabase.getInstance().getReference().child("User_Account_Settings");
viewUserRef = FirebaseDatabase.getInstance().getReference();
setFollowers();
return view;
}
private void setFollowers () {
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mUser.getUser_id());
FirebaseListOptions<UserAccountSettings> options = new FirebaseListOptions.Builder<UserAccountSettings>()
.setLayout(R.layout.layout_user_listitem)
.setLifecycleOwner(getActivity())
.setQuery(query,UserAccountSettings.class)
.build();
viewfollowersadapter = new FirebaseListAdapter(options) {
#Override
protected void populateView(View v, Object model, final int position) {
String newfol = getRef(position).getKey();
final TextView username = v.findViewById(R.id.username);
final CircleImageView profile_image = v.findViewById(R.id.profile_image);
viewFollowersref.child(newfol).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("username")) {
String myusername = dataSnapshot.child("username").getValue().toString();
username.setText(myusername);
}
if (dataSnapshot.hasChild("profileimage")) {
String myimage = dataSnapshot.child("profileimage").getValue().toString();
if (myimage.isEmpty()) {
profile_image.setImageResource(R.drawable.pro_pic);
} else {
Picasso.with(getActivity()).load(myimage).placeholder(R.drawable.pro_pic).into(profile_image);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("calling_activity", "Search_Activity");
profileIntent.putExtra("intent_user", mUserList.get(position));
startActivity(profileIntent);
}
});
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(getActivity(), ProfileActivity.class);
profileIntent.putExtra("calling_activity", "Search_Activity");
profileIntent.putExtra("intent_user", mUserList.get(position));
startActivity(profileIntent);
}
});
Query userQuery = viewUserRef
.child("Users")
.orderByChild("user_id");
userQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: found user: " +
singleSnapshot.getValue(User.class).getUsername());
mUserList.add(singleSnapshot.getValue(User.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
vfollowerslistview.setAdapter(viewfollowersadapter);
}
}
I cant seem to fit the entirw code in.
According to your comment, you are getting the following error:
Caused by: java.langCaused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.hope.myapplication.Models.User.getUser_id()' on a null object reference
Because your mUser object on which you are calling getUser_id() method has the value of null. This is happening because you haven't initialized the User object in your code at all. To solve this, please change the following line of code:
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mUser.getUser_id());
to
Query query = FirebaseDatabase.getInstance().getReference()
.child("Followers")
.child(mAuth.getCurrentUser().getUid());
In which mAuth.getCurrentUser() return a FirebaseUser object, so you can get the correct uid.

How to add Search Filters in android based on Firebase Real-time database?

I'm building an app which ask user to register their name, email, phone no and Blood Type.
Below is my Firebase database structure:
and my Screenshot of app is
How do I add search bar or filters show as per Blood type key , such that user can filters according to Blood Type. If I in requirment of B negative Blood..I'll use drop down menu for Blood I need to search and when pressed on search button will only show me the Blood group registered as B negative in firebase Database i.e as per key blood_group.
Here is my code I use to upload the user details:
public class EnquiryActivity extends AppCompatActivity {
//UI
Button btnRequest;
EditText edtName,edtBlood,edtPlace,edtMobile,edtEmail;
//DB
DatabaseReference mHelper;
FirebaseAuth mAuth;
//progress
ProgressDialog mProgress;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enquiry);
//initialisation
edtBlood=(EditText)findViewById(R.id.enq_blood);
edtMobile=(EditText)findViewById(R.id.enq_mobile);
edtEmail=(EditText)findViewById(R.id.enq_email);
edtName=(EditText)findViewById(R.id.enq_name);
edtPlace=(EditText)findViewById(R.id.enq_place);
btnRequest=(Button)findViewById(R.id.button2);
//firebase
mHelper= FirebaseDatabase.getInstance().getReference();
final String mCurrentUser=FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
mAuth=FirebaseAuth.getInstance();
//progress
mProgress=new ProgressDialog(this);
mProgress.setTitle("Loading");
mProgress.setMessage("Please wait..");
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProgress.show();
String blood=edtBlood.getText().toString();
String name=edtName.getText().toString();
String mobile=edtMobile.getText().toString();
String email=edtEmail.getText().toString();
String place=edtPlace.getText().toString();
String temp=blood.toUpperCase();
if(!TextUtils.isEmpty(blood)||!TextUtils.isEmpty(name)||!TextUtils.isEmpty(mobile)||
!TextUtils.isEmpty(place)){
HashMap<String, String> userMap = new HashMap<>();
userMap.put("name", name);
userMap.put("blood_group",blood);
userMap.put("email", email);
userMap.put("mobile", mobile);
userMap.put("place","Location:- " + place);
mHelper.child("Help").child(mCurrentUser).setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
mProgress.dismiss();
Toast.makeText(getApplicationContext(), "Registered Successfully..!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(),"Please enter the details in all fields",Toast.LENGTH_LONG).show();
}
}
});
}
}
and I retrive the data using below code
/**
* A simple {#link Fragment} subclass.
*/
public class DonorListFragment extends Fragment {
private RecyclerView mDonorList;
private DatabaseReference mFriendsDatabase;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private ProgressDialog mDonorProgress;
private String mCurrent_user_id;
private View mMainView;
public DonorListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_donor_list, container, false);
mDonorList = (RecyclerView)mMainView.findViewById(R.id.donor_recyclerview);
mAuth = FirebaseAuth.getInstance();
mCurrent_user_id = mAuth.getCurrentUser().getUid();
mDonorProgress=new ProgressDialog(getContext());
mDonorProgress.setTitle("Logging In");
mDonorProgress.setMessage("Please Wait...");
mDonorProgress.setCanceledOnTouchOutside(false);
mDonorProgress.show();
mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mDonorList.setHasFixedSize(true);
LinearLayoutManager linearVertical = new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
mDonorList.setLayoutManager(linearVertical);
DividerItemDecoration mDividerItemDecoration = new DividerItemDecoration(
mDonorList.getContext(),
linearVertical.getOrientation()
);
mDonorList.addItemDecoration(mDividerItemDecoration);
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Donors, DonorsViewHolder> friendsRecyclerViewAdapter = new FirebaseRecyclerAdapter<Donors, DonorsViewHolder>(
Donors.class,
R.layout.users_single_layout,
DonorsViewHolder.class,
mUsersDatabase
) {
#Override
protected void populateViewHolder(final DonorsViewHolder donorsViewHolder, Donors donors, int i) {
donorsViewHolder.setDate(donors.getDate());
final String list_user_id = getRef(i).getKey();
mUsersDatabase.child(list_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String userName = dataSnapshot.child("name").getValue().toString();
String blood=dataSnapshot.child("blood_group").getValue().toString();
String phone=dataSnapshot.child("mobile").getValue().toString();
final String email=dataSnapshot.child("email").getValue().toString();
String address=dataSnapshot.child("place").getValue().toString();
mDonorProgress.hide();
donorsViewHolder.setName(userName);
donorsViewHolder.setBlood(blood);
donorsViewHolder.setEmail(email);
donorsViewHolder.setAddress(address);
donorsViewHolder.setPhone(phone);
final String uri=phone;
donorsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]{"Email", "Call"};
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Select Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Click Event for each item.
if(i == 0){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.putExtra(Intent.EXTRA_TEXT, "mail body");
getActivity().startActivity(Intent.createChooser(intent, ""));
}
if(i == 1){
Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+uri));
// callIntent.setData(Uri.parse("tel:"+uri));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(callIntent);
}
}
});
builder.show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
mDonorList.setAdapter(friendsRecyclerViewAdapter);
}
// viewholder class..
public static class DonorsViewHolder extends RecyclerView.ViewHolder {
View mView;
public DonorsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setBlood(String blood){
TextView userStatusView = (TextView) mView.findViewById(R.id.user_single_blood);
userStatusView.setText(blood.toUpperCase());
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setEmail(String email){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_email);
userNameView.setText(email);
}
public void setPhone(String phone){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_phone);
userNameView.setText(phone);
}
public void setAddress(String address) {
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_address);
address.toUpperCase();
userNameView.setText(address.toUpperCase());
}
public void setDate(String date){
}
}
}
To achieve what you want, you need to execute a query which should look like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query query = usersRef.orderByChild("blood_group").equalTo("Blood Group: " + newText);
In which newText variable can hold any value you want, B positive as well as B negative.
So everytime you create a search you should return a new query. So according to this, every time you want to filter on a new condition, you will need to:
Create a new query based on the new filter:
Query query = usersRef.orderByChild("blood_group").equalTo("Blood Group: " + newText);
Attach a listener to this new created query.
Create a new adapter with the results of this new created query, or update the existing one using notifydatasetchanged() method.

Firebase and Android - Chat Message and OnClickListener

I learn Firebase and I found this project: https://github.com/firebase/FirebaseUI-Android/tree/0.3.1/codelabs/chat
I'm trying to expand this project for setOnClickListener method.
I would like to click on every item of this chat message(chat listview) and see
this in another activity.
For example: I have this chat in: ChatMessageActivity. And I would like show this in ChatMessageDetailsActivity.
Like this:
private Firebase firebaseRef;
private static final String FIREBASE_URL = "https://my-project.firebaseio.com/chat";
FirebaseListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
final EditText mText = (EditText) findViewById(R.id.messageText);
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = mText.getText().toString();
ChatMessage message = new ChatMessage("Android User", text);
firebaseRef.push().setValue(message);
mText.setText("");
}
});
final ListView listView = (ListView) this.findViewById(R.id.list);
listAdapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
android.R.layout.two_line_list_item, firebaseRef) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
((TextView)v.findViewById(android.R.id.text1)).setText(model.getName());
((TextView)v.findViewById(android.R.id.text2)).setText(model.getText());
}
};
listView.setAdapter(listAdapter);
firebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
public void onChildRemoved(DataSnapshot dataSnapshot) { }
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
public void onCancelled(FirebaseError firebaseError) { }
});
}
#Override
public View getView(View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if ( row == null || (row.getTag() == null)) {
holder = new ViewHolder();
holder.chatName = (TextView) row.findViewById(R.id.detsName);
holder.chatText = (TextView) row.findViewById(R.id.detsText);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
holder.chatName.setText(holder.chatMessage.getName());
holder.chatText.setText(holder.chatMessage.getText());
final ViewHolder finalHolder = holder;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChatMessage.this, ChatMessageDetails.class);
startActivity(i);
}
});
return row;
}
public class ViewHolder {
ChatMessage chatMessage;
TextView chatName;
TextView chatText;
}
#Override
protected void onDestroy() {
super.onDestroy();
listAdapter.cleanup();
}
}
But getView(at the bottom) method doesn't work. I had this in my old project without Firebase and internet connection. It worked. But now I'm trying to implement this in Chat Project but without positive results.
Is in Firebase some inside method to do this?
Does somebody has some preposition how to develop this listView with SetOnClickListener method with Firebase in AndroidStudio?

Categories

Resources