Search not displaying results - java

I am trying to search for users via their username from Fire-base database, but when I type the username in the search filed it shows a blank list-view. Here's what I've done so far.
SearchActivity.java
package com.example.logindesign;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.logindesign.UserListAdapter;
import com.example.logindesign.users;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* Created by User on 5/28/2017.
*/
public class SearchActivity extends AppCompatActivity {
private static final String TAG = "SearchActivity";
private static final int ACTIVITY_NUM = 1;
private Context mContext = SearchActivity.this;
//widgets
private EditText mSearchParam;
private ListView mListView;
//vars
private List<users> mUserList;
UserListAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchParam = (EditText) findViewById(R.id.search);
mListView = (ListView) findViewById(R.id.listView);
Log.d(TAG, "onCreate: started.");
hideSoftKeyboard();
initTextListener();
}
private void initTextListener(){
Log.d(TAG, "initTextListener: initializing");
mUserList = new ArrayList<>();
mSearchParam.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = mSearchParam.getText().toString().toLowerCase(Locale.getDefault());
searchForMatch(text);
}
});
}
private void searchForMatch(String keyword){
Log.d(TAG, "searchForMatch: searching for a match: " + keyword);
mUserList.clear();
//update the users list view
if(keyword.length() ==0){
}else{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username").equalTo(keyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user:" + Objects.requireNonNull(Objects.requireNonNull(singleSnapshot.getValue(users.class)).toString()));
mUserList.add(singleSnapshot.getValue(users.class));
//update the users list view
updateUsersList();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void updateUsersList(){
Log.d(TAG, "updateUsersList: updating users list");
mAdapter = new UserListAdapter(SearchActivity.this, R.layout.layout_user_listitem, mUserList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected user: " + mUserList.get(position).toString());
//navigate to profile activity
}
});
}
private void hideSoftKeyboard(){
if(getCurrentFocus() != null){
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
}
UserListAdapter.java
package com.example.logindesign;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.util.List;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by User on 9/17/2017.
*/
public class UserListAdapter extends ArrayAdapter<users> {
private static final String TAG = "UserListAdapter";
private LayoutInflater mInflater;
List<users> mUsers = null;
private int layoutResource;
private Context mContext;
public UserListAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<users> objects) {
super(context, resource, objects);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutResource = resource;
this.mUsers = objects;
}
private static class ViewHolder{
TextView username, email;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.username = convertView.findViewById(R.id.username);
holder.email = convertView.findViewById(R.id.email);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.username.setText(Objects.requireNonNull(getItem(position)).getUsername());
holder.email.setText(Objects.requireNonNull(getItem(position)).getEmail());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username")
.equalTo(Objects.requireNonNull(getItem(position)).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot: dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
Objects.requireNonNull(singleSnapshot.getValue(users.class)));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return convertView;
}
}
The results are like this. If you look closely you'll see there's a card-view for the info to be displayed but somehow it's hidden:

U need to pass the value of the list here :
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username").equalTo(keyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user:" + Objects.requireNonNull(Objects.requireNonNull(singleSnapshot.getValue(users.class)).toString()));
mUserList.add(singleSnapshot.getValue(users.class));
//update the users list view
updateUsersList(mUserList);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private void updateUsersList(List<users> mUserList){
////
}

It's for MainActivity.class
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
if (user.getUsername().equals(keyword)) {
mUserList.add(user);
//update the users list view
updateUsersList(mUserList);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
and your User class should look like this :
package com.example.spacing.Model;
public class User {
private String username;
private String phone;
private String id;
private String imageURL;
private String email;
public User(String username, String email ,String phone, String id, String imageURL) {
this.username = username;
this.email=email;
this.phone = phone;
this.id = id;
this.imageURL = imageURL;
}
public String getImageURL() {
return imageURL;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}

Related

Update and delete functions not working in Firebase

I am developing a bus booking app. But I have a problem with the update and delete function. I am able to update the timings and price. But whenever I try to update the source or destination or bus number...my app gets stuck. When I checked my Firebase realtime database....it looks as if the value is stuck in an infinite loop...as the updated value...keeps getting changed from the old to the new value and new value to the old value continuously. This is causing my app to get stuck. I have two files with regard to this.
EditBus.java
package com.example.busticketbooking;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class Edit_Bus extends AppCompatActivity {
//Variables
public EditText busNumEdit,srcEdit,destEdit,timingsEdit,priceEdit;
private DatabaseReference databaseReference;
public String BusID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_bus);
busNumEdit =findViewById(R.id.BusNumber);
srcEdit=findViewById(R.id.source);
destEdit=findViewById(R.id.dest);
timingsEdit=findViewById(R.id.timings);
priceEdit=findViewById(R.id.price);
Button deleteButton = findViewById(R.id.deletebtn);
Button updateButton = findViewById(R.id.updatebtn);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
BusRVModel busRVModel = getIntent().getParcelableExtra("Bus");
if(busRVModel !=null){
busNumEdit.setText(busRVModel.getBusNum());
srcEdit.setText(busRVModel.getSrc());
destEdit.setText(busRVModel.getDest());
timingsEdit.setText(busRVModel.getTimings());
priceEdit.setText(busRVModel.getPrice());
BusID= busRVModel.getBusID();
}
databaseReference= firebaseDatabase.getReference("Bus").child(BusID);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String busNumVar= busNumEdit.getText().toString();
String srcVar=srcEdit.getText().toString();
String destVar=destEdit.getText().toString();
String timingsVar=timingsEdit.getText().toString();
String priceVar=priceEdit.getText().toString();
Map<String,Object> map=new HashMap<>();
map.put("busNum", busNumVar);
map.put("src",srcVar);
map.put("dest",destVar);
map.put("timings",timingsVar);
map.put("price",priceVar);
map.put("busID",BusID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.updateChildren(map);
Toast.makeText(Edit_Bus.this, "Bus updated", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Edit_Bus.this, "Update Error", Toast.LENGTH_SHORT).show();
}
});
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteBus();
}
});
}
private void deleteBus(){
databaseReference.removeValue();
Toast.makeText(this, "Bus Deleted!!!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
}
BusRVModel.java
package com.example.busticketbooking;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class BusRVModel implements Parcelable{
private String busNum;
private String src;
private String dest;
private String timings;
private String price;
private String BusID;
public BusRVModel() {
}
public BusRVModel(String busNum, String src, String dest, String timings, String price, String busID ) {
this.busNum = busNum;
this.src = src;
this.dest = dest;
this.timings = timings;
this.price = price;
BusID = busID;
}
protected BusRVModel(Parcel in) {
busNum = in.readString();
src = in.readString();
dest = in.readString();
timings = in.readString();
price = in.readString();
BusID = in.readString();
}
public static final Creator<BusRVModel> CREATOR = new Creator<BusRVModel>() {
#Override
public BusRVModel createFromParcel(Parcel in) {
return new BusRVModel(in);
}
#Override
public BusRVModel[] newArray(int size) {
return new BusRVModel[size];
}
};
public String getBusNum() {
return busNum;
}
public void setBusNum(String busNum) {
this.busNum = busNum;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getBusID() {
return BusID;
}
public void setBusID(String busID) {
BusID = busID;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(busNum);
parcel.writeString(src);
parcel.writeString(dest);
parcel.writeString(timings);
parcel.writeString(price);
parcel.writeString(BusID);
}
}
AddBus.java
package com.example.busticketbooking;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Add_Bus extends AppCompatActivity {
private EditText busNum,src,dest,timings,price;
private Button button;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private String BusID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_bus);
busNum=findViewById(R.id.BusNumber);
src=findViewById(R.id.source);
dest=findViewById(R.id.dest);
timings=findViewById(R.id.timings);
price=findViewById(R.id.price);
button=findViewById(R.id.btn);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Bus");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String busNumVar=busNum.getText().toString();
String srcVar=src.getText().toString();
String destVar=dest.getText().toString();
String timingsVar=timings.getText().toString();
String priceVar=price.getText().toString();
BusID=busNumVar;
BusRVModel busRVModel=new BusRVModel(busNumVar,srcVar,destVar,timingsVar,priceVar,BusID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child(BusID).setValue(busRVModel);
Toast.makeText(Add_Bus.this, "Bus added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Add_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Add_Bus.this, "Error is: "+error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
The problem is here:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.updateChildren(map);
Toast.makeText(Edit_Bus.this, "Bus updated", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Edit_Bus.this, "Update Error", Toast.LENGTH_SHORT).show();
}
});
You're adding a listener to the database by calling addValueEventListener, which is documented as:
This method is triggered once when the listener is attached and again every time the data, including children, changes.
Now inside the onDataChange you modify the data at databaseReference, and as the documentation says that leads to onDataChange being called again, which leads to you updating the data again, which leads to...
Since it seems you only want to update the data once, you can use addListenerForSingleValueEvent to prevent retriggering onDataChange:
// 👇
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
...

Failed to Sum up the recyclerview items value

I am totally new to Android Studio.
I created recycleview for Budgeting. I created a Budget description and budget value for each item.
I am trying to sum up all the values of the recyclerview. I have tried different methods over the night but failed to do. PLease help!!!
Adapter:
package com.example.personalwallet.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
private ArrayList<Budget> userlist;
private DatabaseReference databaseReference;
private String uId;
int sum=0;
public recyclerAdapter(ArrayList<Budget> userlist,String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView nameTxt,amountTXT;
CardView rootCardView;
ImageView deleteSupplierIV;
public MyViewHolder(final View view){
super(view);
nameTxt = view.findViewById(R.id.name);
amountTXT = view.findViewById(R.id.value);
rootCardView = itemView.findViewById(R.id.single_supplier_cardview_id);
deleteSupplierIV = itemView.findViewById(R.id.delete_supplier_IV);
}
}
#NonNull
#Override
public recyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new MyViewHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull recyclerAdapter.MyViewHolder holder, int position) {
Budget user = userlist.get(position);
String name,amount;
name = user.getBudgetDescription();
amount = user.getAmount();
holder.nameTxt.setText(name);
holder.amountTXT.setText(amount);
if (user.isVisibilityStatus()){
holder.deleteSupplierIV.setVisibility(View.GONE);
}
holder.rootCardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.deleteSupplierIV.setVisibility(View.VISIBLE);
user.setVisibilityStatus(false);
return true;
}
});
holder.deleteSupplierIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSupplier(user.getBudgetDescription());
}
private void deleteSupplier(String supplierName) {
DatabaseReference productReference = databaseReference.child(supplierName);
productReference.removeValue();
userlist.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return userlist.size();
}
}
Activity Code:
package com.example.personalwallet.NavCategories;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Adapter.recyclerAdapter;
import com.example.personalwallet.AddBudgetActivity;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.Prevalent.Prevalent;
import com.example.personalwallet.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Budgets extends AppCompatActivity{
private FloatingActionButton addNewBudgetFAB;
private ArrayList<Budget> userlist;
private RecyclerView recyclerView;
private String uId;
DatabaseReference databaseReference;
recyclerAdapter adapter;
TextView TotalBudgetTv;
public int total_budget =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budgets);
userlist = new ArrayList<Budget>();
recyclerView = findViewById(R.id.suppliers_recyclerViewID);
TotalBudgetTv = findViewById(R.id.TotalBudgetTv);
uId = Prevalent.currentOnlineUser.getPhone();
adapter = new recyclerAdapter(userlist,uId);
setUserInfo();
setAdapter();
**for (int i=0; i<userlist.size(); i++){
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}**
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
addNewBudgetFAB = findViewById(R.id.addNewSuppliersFABID);
addNewBudgetFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Budgets.this, AddBudgetActivity.class);
startActivity(intent);
}
});
}
private void setAdapter() {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
private void setUserInfo() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is my model class:
package com.example.personalwallet.Model;
public class Budget {
private String BudgetDescription;
private String amount;
public boolean isVisibilityStatus() {
return visibilityStatus;
}
public void setVisibilityStatus(boolean visibilityStatus) {
this.visibilityStatus = visibilityStatus;
}
private boolean visibilityStatus = true;
public Budget(){}
public Budget(String budgetDescription, String amount) {
BudgetDescription = budgetDescription;
this.amount = amount;
}
public String getBudgetDescription() {
return BudgetDescription;
}
public void setBudgetDescription(String budgetDescription) {
BudgetDescription = budgetDescription;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Try to put your forloop calculation inside onDataChange because in oncreate method your userlist is empty. So when onDataChange called after that new value added to userlist and calculate your total there.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
for (int i=0; i<userlist.size(); i++)
{
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
In the adapter's constructor you will get the ArrayList which contains all data. Here, you can run a for loop. which will read each object one by one and add in sum.
public recyclerAdapter(ArrayList<Budget> userlist, String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
for(int i = 0; i<userlist.size(); i++){
Budget user = userlist.get(i);
sum = sum + user.getAmount();
}
}

Recyclerview not updating after activity restart

So, I'm not sure about the title of this question but here it goes. I have a recyclerview for my chat room. The first time the activity started it has no problem displaying the messages but after pressing the back button back to the main activity showing all chat rooms then click the same chat room again it displays nothing. Then, after sent a message it can display all the messages again. I'm not sure what happened, help, please. Oh, I already tried a few things and browse the internet but because I'm not sure what the keyword is, so I'm quite stuck now
Okay, here is the thing
First main activity, (ignore the other 2 tabs, it's empty)
Main Activity
Then open a chat room
First time open chat room fine
Then press back button, back to MainActivity, then open the same room and no chat displayed
chat room not displaying anything
Then it displays messages again after sending a new messages
new message
I have tried to place notifyDataSetChanged() on various event like onStart, onCreate etc but nothing works;
here is my chat activity
package com.divistant.chat.ui.chat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.divistant.chat.R;
import com.divistant.signup.UserModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
ImageView send;
EditText message;
ScrollView scrollView;
DatabaseReference refrence1;
DatabaseReference refrence2;
RecyclerView rv;
List<ChatModel> chats = new ArrayList<>();
ChatActivityAdapter adapter;
FirebaseUser cUser;
UserModel target;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Log.w("EVENT","ON Create");
Intent intent = getIntent();
target = (new Gson()).fromJson(intent.getStringExtra("target"),UserModel.class);
send = (ImageView)findViewById(R.id.sendButton);
message = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
rv = (RecyclerView) findViewById(R.id.main_chat_rv);
cUser = FirebaseAuth.getInstance().getCurrentUser();
adapter = new ChatActivityAdapter(chats);
final LinearLayoutManager manager = new LinearLayoutManager(ChatActivity.this,
LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(manager);
refrence1 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(cUser.getUid() + "_" + target.getUserId());
refrence2 = FirebaseDatabase.getInstance()
.getReference()
.child("messages")
.child(target.getUserId() + "_" + cUser.getUid());
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("SEND","send message");
if(message.getText().toString().length() > 0){
ChatModel chat = new ChatModel();
chat.setSender(cUser.getEmail());
chat.setMessage(message.getText().toString());
chat.setReceiver(target.getEmailAddress());
chat.setSenderUid(cUser.getUid());
chat.setReceiverUid(target.getUserId());
chat.setTimestamp((new Date()).getTime());
DatabaseReference ref1 = refrence1.push();
ref1.setValue(chat);
DatabaseReference ref2 = refrence2.push();
ref2.setValue(chat);
message.setText("");
}
}
});
refrence1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
Log.e("[CH]","DATACHANGE " + chats.size());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","CANCEL");
}
});
refrence1.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","DB CHANGE");
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
Log.e("[CH]","DB REMOVE");
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Log.e("[CH]","Child Moved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("[CH]","DB ERROR");
}
});
rv.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
Log.e("[CH]","" + adapter.getItemCount());
}
}
Then, here is my ChatActivityAdapter
package com.divistant.chat.ui.chat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.divistant.chat.R;
import com.google.firebase.auth.FirebaseAuth;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ChatActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int VIEW_TYPE_ME = 1;
private static final int VIEW_TYPE_OTHER = 2;
List<ChatModel> mChats;
public void setmChats(List<ChatModel> mChats) {
this.mChats = mChats;
}
public ChatActivityAdapter(List<ChatModel> mChats) {
this.mChats = mChats;
Log.e("ADAPTER","CONSTRUCTED " + mChats.size());
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case VIEW_TYPE_ME:
View viewChatMine = layoutInflater.inflate(R.layout.chat_item, parent, false);
viewHolder = new MyChatViewHolder(viewChatMine);
break;
case VIEW_TYPE_OTHER:
View viewChatOther = layoutInflater.inflate(R.layout.chat_item_other, parent, false);
viewHolder = new OtherChatViewHolder(viewChatOther);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
configureMyChatViewHolder((MyChatViewHolder) holder, position);
} else {
configureOtherChatViewHolder((OtherChatViewHolder) holder, position);
}
}
private void configureMyChatViewHolder(final MyChatViewHolder myChatViewHolder, int position) {
ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
myChatViewHolder.senderMsgTime.setText(date);
myChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
private void configureOtherChatViewHolder(final OtherChatViewHolder otherChatViewHolder, int position) {
final ChatModel chat = mChats.get(position);
SimpleDateFormat sfd = new SimpleDateFormat("hh:mm a");
String date=sfd.format(new Date(chat.timestamp).getTime());
otherChatViewHolder.receiverMsgTime.setText(date);
otherChatViewHolder.txtChatMessage.setText(chat.getMessage());
}
#Override
public int getItemCount() {
return mChats.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.equals(mChats.get(position).senderUid,
FirebaseAuth.getInstance().getCurrentUser().getUid())) {
return VIEW_TYPE_ME;
} else {
return VIEW_TYPE_OTHER;
}
}
private static class MyChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView senderMsgTime;
public MyChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet);
senderMsgTime=(TextView) itemView.findViewById(R.id.senderMsgTime);
}
}
private static class OtherChatViewHolder extends RecyclerView.ViewHolder {
private TextView txtChatMessage, txtUserAlphabet;
private TextView receiverMsgTime;
public OtherChatViewHolder(View itemView) {
super(itemView);
txtChatMessage = (TextView) itemView.findViewById(R.id.text_view_chat_message_ot);
txtUserAlphabet = (TextView) itemView.findViewById(R.id.text_view_user_alphabet_ot);
receiverMsgTime=(TextView) itemView.findViewById(R.id.receiverMsgTime_ot);
}
}
}
Thanks
Thats because you are clearing the list on childevent listener and not adding the new child in list and not passing the list to the adapter.
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
Now change the code by adding the lines
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
chats.clear();
for(DataSnapshot snapshot :dataSnapshot.getChildren()){
ChatModel chat = new ChatModel();
chat.setSender(snapshot.child("sender").getValue(String.class));
chat.setMessage(snapshot.child("message").getValue(String.class));
chat.setReceiver(snapshot.child("receiver").getValue(String.class));
chat.setSenderUid(snapshot.child("senderUid").getValue(String.class));
chat.setReceiverUid(snapshot.child("receiverUid").getValue(String.class));
chat.setTimestamp(1592455659978L);
chats.add(chat);
}
adapter.setmChats(chats);
adapter.notifyDataSetChanged();
rv.scrollToPosition(adapter.getItemCount()-1);
}
in my case i used onResume()
#Override
protected void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
Can you put rv.setAdapter(adapter) after rv.setLayoutManager(manager);?
And you verify if the method onDataChange(...) its always called??
You can use the following code in the adapter where you want to refresh recyclerview, for example in #Override public void onBackPressed(){} function. If your chats array changed, you should refresh this adapter.
mAdapter = new ChatActivityAdapter(context, chats.get(chats.size() - 1), chats);
recyclerView.setAdapter(mAdapter);

Firebase data retrieve and passing it from fragment to new activity not working

I am developing an android app which shows the user with the latest jobs from various fields. When the jobs are displayed and when the user clicks on view more, the job description is not getting displayed.
I have passed data from fragment to new activity and displaying it in the new activity. There is no error but the details are not getting displayed. I have attached the code and the firebase database structure.
Here is the WorkFragment.java file which shows the jobs in recyclerview.
WorkFragment.java
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.database.annotations.Nullable;
import java.util.ArrayList;
public class WorkFragment extends Fragment {
DatabaseReference databaseReference;
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
ArrayList<Jobs> jobs;
MyAdapter adapter;
ProgressDialog pd;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_work, container, false);
recyclerView = view.findViewById(R.id.work);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
pd = new ProgressDialog(getContext());
pd.setMessage("Loading Jobs for you...");
pd.show();
jobs = new ArrayList<Jobs>();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("Jobs");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
Jobs j = ds.getValue(Jobs.class);
jobs.add(j);
}
pd.dismiss();
adapter = new MyAdapter(getContext(), jobs);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
pd.dismiss();
}
});
return view;
}
}
Here is the MyAdapter.java class which does the job for recyclerview.
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Jobs> jobs;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
public MyAdapter(Context c, ArrayList<Jobs> j){
context = c;
jobs = j;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.job, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.jobtitle.setText(jobs.get(position).getJobtitle());
holder.jobtype.setText(jobs.get(position).getJobtype());
holder.companyname.setText(jobs.get(position).getCompany());
holder.location.setText(jobs.get(position).getLocation());
holder.jobdate.setText(jobs.get(position).getJobdate());
holder.viewmore.setText(jobs.get(position).getViewmore());
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Jobs");
holder.viewmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String jobtitle = dataSnapshot.child("jobtitle").getValue(String.class);
String company = dataSnapshot.child("company").getValue(String.class);
String location = dataSnapshot.child("location").getValue(String.class);
String jobtype = dataSnapshot.child("jobtype").getValue(String.class);
String startDate = dataSnapshot.child("startdate").getValue(String.class);
String salary = dataSnapshot.child("salary").getValue(String.class);
String about = dataSnapshot.child("about").getValue(String.class);
String responsiblities = dataSnapshot.child("responsiblities").getValue(String.class);
String musthave = dataSnapshot.child("musthave").getValue(String.class);
String seniority = dataSnapshot.child("seniority").getValue(String.class);
Intent intent = new Intent(context, JobDescription.class);
intent.putExtra("JOBTITLE", jobtitle);
intent.putExtra("COMPANY", company);
intent.putExtra("LOCATION", location);
intent.putExtra("JOBTYPE", jobtype);
intent.putExtra("STARTDATE", startDate);
intent.putExtra("SALARY", salary);
intent.putExtra("ABOUT", about);
intent.putExtra("RESPONSIBLITIES", responsiblities);
intent.putExtra("MUSTHAVE", musthave);
intent.putExtra("SENIORITY", seniority);
context.startActivity(intent);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
}
#Override
public int getItemCount() {
return jobs.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView jobtitle, jobtype, companyname, location, jobdate, viewmore;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
jobtitle = (TextView) itemView.findViewById(R.id.jobTitle);
jobtype = (TextView) itemView.findViewById(R.id.jobType);
companyname = (TextView) itemView.findViewById(R.id.companyName);
location = (TextView) itemView.findViewById(R.id.location);
jobdate = (TextView) itemView.findViewById(R.id.jobDate);
viewmore = (TextView) itemView.findViewById(R.id.viewMore);
}
}
}
Here is the Job.class.
Jobs.java
public class Jobs {
private String jobtitle, jobtype, company, location, jobdate, viewmore, startdate, salary, about, responsiblities, musthave, seniority;
public Jobs() {
}
public Jobs(String jobtitle, String jobtype, String company, String location, String jobdate, String viewmore, String startdate, String salary, String about, String responsiblities, String musthave, String seniority) {
this.jobtitle = jobtitle;
this.jobtype = jobtype;
this.company = company;
this.location = location;
this.jobdate = jobdate;
this.viewmore = viewmore;
this.startdate = startdate;
this.salary = salary;
this.about = about;
this.responsiblities = responsiblities;
this.musthave = musthave;
this.seniority = seniority;
}
public String getJobtitle() {
return jobtitle;
}
public void setJobtitle(String jobtitle) {
this.jobtitle = jobtitle;
}
public String getJobtype() {
return jobtype;
}
public void setJobtype(String jobtype) {
this.jobtype = jobtype;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getJobdate() {
return jobdate;
}
public void setJobdate(String jobdate) {
this.jobdate = jobdate;
}
public String getViewmore() {
return viewmore;
}
public void setViewmore(String viewmore) {
this.viewmore = viewmore;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getResponsiblities() {
return responsiblities;
}
public void setResponsiblities(String responsiblities) {
this.responsiblities = responsiblities;
}
public String getMusthave() {
return musthave;
}
public void setMusthave(String musthave) {
this.musthave = musthave;
}
public String getSeniority() {
return seniority;
}
public void setSeniority(String seniority) {
this.seniority = seniority;
}
}
Here is the JobDescription.java which shows the details of job. In this class, Iam getting details from fragment and displaying it.
JobDescription.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class JobDescription extends AppCompatActivity {
TextView jobtitle, company, location, startDate, salary, aboutText, responsiblityText, musthaveText, jobtypetext, seniority;
Button applyNow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_description);
getSupportActionBar().setTitle("Job Description");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
jobtitle = (TextView) findViewById(R.id.jobTitle);
company = (TextView) findViewById(R.id.company);
location = (TextView) findViewById(R.id.location);
startDate = (TextView) findViewById(R.id.startDate);
salary = (TextView) findViewById(R.id.salary);
aboutText = (TextView) findViewById(R.id.aboutText);
responsiblityText = (TextView) findViewById(R.id.responsiblityText);
musthaveText = (TextView) findViewById(R.id.musthaveText);
jobtypetext = (TextView) findViewById(R.id.jobtypetext);
seniority = (TextView) findViewById(R.id.seniority);
applyNow = (Button) findViewById(R.id.applyBtn);
jobtitle.setText(getIntent().getStringExtra("JOBTITLE"));
company.setText(getIntent().getStringExtra("COMPANY"));
location.setText(getIntent().getStringExtra("LOCATION"));
startDate.setText(getIntent().getStringExtra("STARTDATE"));
salary.setText(getIntent().getStringExtra("SALARY"));
aboutText.setText(getIntent().getStringExtra("ABOUT"));
responsiblityText.setText(getIntent().getStringExtra("RESPONSIBLITIES"));
musthaveText.setText(getIntent().getStringExtra("MUSTHAVE"));
jobtypetext.setText(getIntent().getStringExtra("JOBTYPE"));
seniority.setText(getIntent().getStringExtra("SENIORITY"));
}
}
Here is the firebase database structure.
In your adapter you dont need to add valueeventlistner , all you need is to pass data to descriptionactivity as shown below
holder.viewmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, JobDescription.class);
intent.putExtra("JOBTITLE", jobs.getJobtitle);
intent.putExtra("COMPANY", jobs.getcompany);
context.startActivity(intent);
}
});

How can I get the key of an item populated from firebase database clicked in the recyclerview

I have a very serious problem. I am using a RecyclerView to populate data(a list of users) from Firebase into my application. Now the problem is that how to reference their respective userIds when a user clicks any of them so it can be used to set the title of the activity's action bar that will be opened. I tried using the getRef() method but it could not be resolved. Below is my code.
My StudentsList
package com.dreamlazerstudios.gtuconline;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import static android.content.ContentValues.TAG;
public class StudentsList extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<Students> listData;
RecyclerView recyclerView;
StudentsList.MyAdapter adapter;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_students_list);
setTitle("List of Students");
recyclerView = findViewById(R.id.students_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new StudentsList.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("Students");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Students students = dataSnapshot.getValue(Students.class);
listData.add(students);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#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) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<Students> list;
public MyAdapter(List<Students> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
Students students = list.get(position);
String list_user_id = getRef(position).getKey();
holder.news_topic.setText(students.getName());
holder.news_body.setText(students.getProgramme());
if (students.getOnline() == true) {
holder.online.setVisibility(View.VISIBLE);
} else {
holder.online.setVisibility(View.INVISIBLE);
}
Picasso.with(holder.news_image.getContext()).load(students.getThumb_image()).placeholder(R.drawable.student_icon_17870).into(holder.news_image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chat_intent = new Intent(StudentsList.this, ChatActivity.class);
chat_intent.putExtra("user_id", list_user_id );
startActivity(chat_intent);
}
});
}
#NonNull
#Override
public StudentsList.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_layout, parent, false);
return new StudentsList.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView news_topic, news_body;
CircleImageView news_image;
ImageView online;
public ViewHolder(View itemView) {
super(itemView);
news_topic = itemView.findViewById(R.id.user_single_name);
news_body = itemView.findViewById(R.id.user_single_status);
news_image = itemView.findViewById(R.id.user_single_image);
online = itemView.findViewById(R.id.online_status_icon);
}
}
#Override
public int getItemCount() {
return list.size();
}
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
My model class
package com.dreamlazerstudios.gtuconline;
/**
* Created by Gabriel Hagan on 16/05/2018 at 23:10.
*/
public class Students {
String name;
String programme;
String thumb_image;
Boolean online;
public Boolean getOnline() {
return online;
}
public void setOnline(Boolean online) {
this.online = online;
}
public Students() {
}
public Students(String name, String programme, String thumb_image, Boolean online) {
this.name = name;
this.programme = programme;
this.thumb_image = thumb_image;
this.online = online;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProgramme() {
return programme;
}
public void setProgramme(String programme) {
this.programme = programme;
}
public String getThumb_image() {
return thumb_image;
}
public void setThumb_image(String thumb_image) {
this.thumb_image = thumb_image;
}
}
My ChatActivity
package com.dreamlazerstudios.gtuconline;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ChatActivity extends AppCompatActivity {
private DatabaseReference rootRef;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
private String mChatUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mChatUser = getIntent().getStringExtra("user_id");
rootRef.child("Users").child("Students").child(mChatUser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String chat_user_name = dataSnapshot.child("name").getValue().toString();
setTitle(chat_user_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
rootRef.child("Chat").child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
My database snapshot
You can get the key from the DataSnapshot you are getting in onChildAdded. Instead of having a list of students in your adapter, you could keep the list of DataSnapshots. Then you could do something like this:
In StudentsList, change:
List<Students> listData;
To:
List<DataSnapshot> listData;
Also, change onChildAdded:
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listData.add(dataSnapshot);
//Should probably move these since they don't need to get called for every item.
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
Then in your adapter:
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
DataSnapshot studentSnapshot = list.get(position);
String list_user_id = studentSnapshot.getKey();
Students students = studentSnapshot.getValue(Students.class)
//The rest unchanged
Inside onBindViewHolder method you can get the key of the user that you are looking for using the following line of code:
String list_user_id = getItem(position);
getRef() is used to obtain a reference to the source location for the snapshot. So you can only use this method on a snapshot object. It returns a DatabaseReference and takes no argument. Below an example:
DatabaseReference ref = dataSnapshot.child("users").getRef();

Categories