Passing Values Java classes - java

I've a problem with values from firebase database and a simple textview where to show them.
public class FindReportActivity extends Activity implements View.OnClickListener{
EditText editTextFindReport;
TextView textViewCommento;
TextView textViewGravita;
ImageView imageViewFindReport;
String cdt;
Report report;
ReportDAO reportDAO = new ReportDAO();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_report);
imageViewFindReport = (ImageView) findViewById(R.id.imageViewFindReport);
editTextFindReport = (EditText) findViewById(R.id.editTextCDT);
textViewCommento= (TextView) findViewById(R.id.textViewcommento);
textViewGravita= (TextView) findViewById(R.id.textViewgravita);
imageViewFindReport.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if( v == imageViewFindReport){
cdt = editTextFindReport.getText().toString().trim();
textViewCommento.setText(reportDAO.findReport(cdt));
}
}
}
here ReportDAO class
public class ReportDAO {
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference databaseReference = firebaseDatabase.getReference();
String commento = "non";
public ReportDAO(){ }
public String findReport(String cdt){
DatabaseReference refReport = databaseReference.child("Report").child(cdt).child("commento");
refReport.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
commento = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return commento;
}
when i click the imageview, the frist time is blank, second time is correct value... why?

You need to implement a listener that waits for the commento to get available, because the findReport method works asynchronous.

Related

When I click on different person Chat room the app opening the same person chat

I'm facing a problem please check find the problem: When I click on a different chat room it opening the same chat room as you can see below:
Here is the Chatsfragment.java (Left side screen)
public class ChatsFragment extends Fragment{
private RecyclerView recyclerView;
private FriendsAdapter userAdapter;
private List<Users> mUsers;
FirebaseUser fuser;
DatabaseReference reference;
private List<String> usersList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_chats, container, false);
recyclerView = view.findViewById(R.id.ChatsFragment_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
usersList = new ArrayList<>();
fuser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
usersList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Chat chat=snapshot.getValue(Chat.class);
assert chat != null;
if (chat.getSender().equals(fuser.getUid())) {
usersList.add(chat.getReceiver());
}
if (chat.getReceiver().equals(fuser.getUid())) {
usersList.add(chat.getSender());
}
}
Set<String> hashSet = new HashSet<String>(usersList);
usersList.clear();
usersList.addAll(hashSet);
readChats();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
UpdateToken();
return view;
}
private void UpdateToken() {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String refreshToken = FirebaseInstanceId.getInstance().getToken();
Token token = new Token(refreshToken);
FirebaseDatabase.getInstance().getReference("Tokens").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(token);
}
private void readChats() {
mUsers=new ArrayList<>();
reference= FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//mUsers.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Users user=snapshot.getValue(Users.class);
for(String id:usersList)
{
assert user != null;
if (user.getUser_id().equals(id)) {
mUsers.add(user);
}
}
}
userAdapter=new FriendsAdapter(getContext(),mUsers,true);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
Here is the MessageActivity.java(Right side screen)
public class MessageActivity extends AppCompatActivity {
CircleImageView profile_image;
TextView username,fullname;
FirebaseUser fuser;
DatabaseReference reference;
private Toolbar toolbar;
Intent intent;
boolean notify = false;
TextView btn_send;
EditText text_send;
MessageAdapter messageAdapter;
List<Chat> mchat;
RecyclerView recyclerView;
String userid;
private APIService apiService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
toolbar = findViewById(R.id.MessageActivity_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = (TextView)findViewById(R.id.MessageActivity_userName);
fullname = (TextView)findViewById(R.id.MessageActivity_fullname);
profile_image = (CircleImageView)findViewById(R.id.MessageActivity_user_img);
btn_send =findViewById(R.id.MessageActivity_btn_send);
text_send = findViewById(R.id.MessageActivity_text_send);
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
recyclerView = findViewById(R.id.MessageActivity_recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
intent = getIntent();
userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
username.setText(user.getUsername());
fullname.setText(user.getFullName());
Glide.with(MessageActivity.this)
.load(user.getProfilePhoto())
.into(profile_image);
readMesagges(fuser.getUid(), userid, user.getProfilePhoto());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
btn_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notify = true;
String msg = text_send.getText().toString();
if (!msg.equals("")){
sendMessage(fuser.getUid(), userid, msg);
} else {
Toast.makeText(MessageActivity.this, "You can't send empty message", Toast.LENGTH_SHORT).show();
}
text_send.setText("");
closeKeyboard();
}
});
}
private void sendMessage(String sender, final String receiver, String message){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
hashMap.put("isseen", false);
reference.child("Chats").push().setValue(hashMap);
final String msg = message;
reference = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Users user = dataSnapshot.getValue(Users.class);
if (notify) {
sendNotifiaction(receiver, user.getUsername(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendNotifiaction(String receiver, final String username, final String message) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(receiver);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.ic_launcher, username+":"+message, "New Message",
userid);
NotificationSender sender = new NotificationSender(data, token.getToken());
apiService.sendNotification(sender).enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.code() == 200){
if (response.body().success != 1){
Toast.makeText(MessageActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readMesagges(final String myid, final String userid, final String imageurl){
mchat = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mchat.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(myid)){
mchat.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, mchat, imageurl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void closeKeyboard(){
View view = this.getCurrentFocus();
if(view != null){
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} }
Here is the FriendsAdapter.java
public FriendsAdapter(Context mcontext, List<Users> muser, boolean ischat) {
this.mcontext = mcontext;
this.muser = muser;
this.ischat = ischat;
}
#NonNull
#Override
public FriendsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.friends_single_layout,parent,false);
return new FriendsAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsAdapter.ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
users = muser.get(position);
holder.username.setText(users.getFullName());
// holder.fullname.setText(users.getFullName());
Glide.with(mcontext)
.load(users.getProfilePhoto())
.into(holder.profileimage);
if (ischat){
lastMessage(users.getUser_id(), holder.last_msg);
} else {
holder.last_msg.setText(users.getFullName());
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MessageActivity.class);
intent.putExtra("userid",users.getUser_id());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return muser.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username,last_msg;
public CircleImageView profileimage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.FriendSingle_userName);
last_msg = itemView.findViewById(R.id.FriendSingle_lastMsg);
profileimage = itemView.findViewById(R.id.FriendSingle_user_img);
}
}
//check for last message
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText(users.getFullName());
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}}
Again, the problem is whenever user click on recyclerView item it shows the same chat room, please find the errer and let me know as soon as possible.
Thanks for your time
From what you've posted (there seems to be part of FriendsAdapter.java missing), it looks like the issue is in your FriendsAdapter. You have probably defined the users variable at the Adapter level, but it should be defined at the ViewHolder level or just used as a local variable.
Your are calling users = muser.get(position) in your bindViewHolder method so if users is defined at adapter level when your onClickListener is fired the users variable will be set to the user of the last cell, instead of the user object associated with the cell clicked.
So, remove the definition of users from adapter level (probably looks like this):
User users;
And either use users as a local variable inside the bindViewHolder method:
User users = muser.get(position);
Or put the definition inside your ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder {
public User users;
public TextView username,last_msg;
public CircleImageView profileimage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.FriendSingle_userName);
last_msg = itemView.findViewById(R.id.FriendSingle_lastMsg);
profileimage = itemView.findViewById(R.id.FriendSingle_user_img);
}
}

Unable to retrieve data from Firebase - Android Studio (Java)

I am trying to read a value from a database but does not seem to be working. The purpose of the code is to take in a counter value from a user's UID in Firebase, that will change the source of an image. The counter is changed in another activity and works fine. I feel I am close but not sure what do do next. I have tried to print out the value but it does not print in the console.
Full disclaimer, I am new to android development and firebase so I apologise in advance if it is a simple mistake/correction.
Activity calling the database UPDATED:
public class Menu extends AppCompatActivity {
private static final String TAG = "Menu";
Button btn;
public ImageView image;
public static int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Add an image
image = findViewById(R.id.imageView2);
image.setImageResource(R.drawable.g1);
//image.setImageResource(getIntent().getIntExtra("myImageResource",R.drawable.g1));
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("counter");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
menuCounter uCount = dataSnapshot.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).getValue(menuCounter.class);
System.out.println("Simon says" + uCount.counter);
counter = uCount.counter;
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
System.out.println("Counter is: " + counter);
if (counter == 1) {
image.setImageResource(R.drawable.g2);
}
btn = findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent WIP = new Intent(Menu.this, WIP.class);
startActivity(WIP);
}
});
}
}
Getter class:
package com.alanlyne.tbm;
public class menuCounter {
int counter;
public menuCounter() {
}
public menuCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
Activity changing the counter value:
public class WIP extends AppCompatActivity {
Button btn;
DatabaseReference databaseName;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wip);
databaseName = FirebaseDatabase.getInstance().getReference("counter");
btn = findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Menu.counter = 1;
Intent act2= new Intent(WIP.this,Menu.class);
// act2.putExtra("myImageResource", R.drawable.g2);
startActivity(act2);
addCounter();
}
});
}
private void addCounter() {
Menu.counter = 1;
String id = databaseName.push().getKey();
menuCounter counter = new menuCounter(Menu.counter);
databaseName.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(counter);
}
}
Firebase image:

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.

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.

Categories

Resources