Java
Here is the code of fragment of my app and when I run it my app crashes as soon as I start the app got Customer home fragment it crashes, In logcat its showing there is error in CustomerHomefragemnt so here's the code as I am not being able to troubleshoot it Please answer if someone can help. Here is my fragment code`
public class CustomerHomeFragment extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
RecyclerView recyclerView;
private List<UpdateDishModel> updateDishModelList;
private CustomerHomeAdapter adapter;
String State, City, Sub;
DatabaseReference dataaa, databaseReference;
SwipeRefreshLayout swipeRefreshLayout;
SearchView searchView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_customerhome, null);
setHasOptionsMenu(true);
recyclerView = v.findViewById(R.id.recycle_menu);
recyclerView.setHasFixedSize(true);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.move);
recyclerView.startAnimation(animation);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
updateDishModelList = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipelayout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimaryDark, R.color.green);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
dataaa = FirebaseDatabase.getInstance()
.getReference("Customer").child(userid);
dataaa.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Customer cust = dataSnapshot.getValue(Customer.class);
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
customermenu();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
return v;
}
#Override
public void onRefresh() {
customermenu();
}
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
}
private void search(final String searchtext) {
ArrayList<UpdateDishModel> mylist = new ArrayList<>();
for (UpdateDishModel object : updateDishModelList) {
if (object.getDishes().toLowerCase().contains(searchtext.toLowerCase())) {
mylist.add(object);
}
}
adapter = new CustomerHomeAdapter(getContext(), mylist);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search, menu);
MenuItem menuItem = menu.findItem(R.id.Searchdish);
searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search Dish");
}
}
```
`here is my Homeadapter code`
public class CustomerHomeAdapter extends
RecyclerView.Adapter<CustomerHomeAdapter.ViewHolder>
{
private Context mcontext;
private List<UpdateDishModel>updateDishModellist;
DatabaseReference databaseReference;
public CustomerHomeAdapter(Context context,List<UpdateDishModel>updateDishModellist)
{
this.updateDishModellist=updateDishModellist;
this.mcontext=context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=
LayoutInflater.from(mcontext)
.inflate(R.layout.customer_menudish,parent,false);
return new CustomerHomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final UpdateDishModel updateDishModel=updateDishModellist.get(position);
Glide.with(mcontext).load(updateDishModel.getImageURL()).into(holder.imageView);
holder.Dishname.setText(updateDishModel.getDishes());
updateDishModel.getRandomUID();
updateDishModel.getChefId();
holder.price.setText("Price: ₹ " + updateDishModel.getPrice());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mcontext,OrderDish.class);
intent.putExtra("FoodMenu",updateDishModel.getRandomUID());
intent.putExtra("ChefId",updateDishModel.getChefId());
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return updateDishModellist.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView Dishname,price;
ElegantNumberButton additem;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.menu_image);
Dishname=itemView.findViewById(R.id.dishname);
price=itemView.findViewById(R.id.dishprice);
additem=itemView.findViewById(R.id.number_btn);
}
}
}
I think error is in this code as i am not able to trouble shoot is please help me with this
private void customermenu() {
swipeRefreshLayout.setRefreshing(true);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
updateDishModelList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
UpdateDishModel updateDishModel =
snapshot1.getValue(UpdateDishModel.class);
updateDishModelList.add(updateDishModel);
}
}
adapter = new CustomerHomeAdapter(getContext(), updateDishModelList);
recyclerView.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
swipeRefreshLayout.setRefreshing(false);
}
});
enter image description here
enter image description here
From your code, your issue seems to be on below line:
FirebaseDatabase.getInstance().getReference("FoodSupplyDetails")
.child(State).child(City).child(Sub);
Error tells you you cannot pass null for ".child()". So it is telling you the values for State, City and Sub are null. You can confirm this by going to your Firebase's console database and seeing the data structure for the corresponding "Customer" with the firebase id.
Please check your Firebase database and make sure the customer data exists.
Before you run your query you should make sure the values are not null.
if (State != null && City != null && Sub != null) {
// Run your query here
} else {
Log.d("TAG", "Data provided is null")
}
When you are fetching customer's information, try logging that and check which of them is null:
String State, City, Sub;
//...
State = cust.getState();
City = cust.getCity();
Sub = cust.getSuburban();
Log.d("TAG", State);
Log.d("TAG", City);
Log.d("TAG", Sub);
// call customermenu now
customermenu();
The error tells you you cannot pass null for ".child()". So it is telling you the values for data(stored in the firebase database) are null. You can confirm this by going to your Firebase's console database and seeing the data structure corresponding with the firebase id.
Related
I have an ImageView which acts as a like button and when a user clicks on it, it changes to a different ImageView which indicates that that comment was liked. The problem is that when I click on one, more than one gets selected. Let's say that there are 6 comments in the list and I "like" the 4th comment, other ones get "liked" also which shouldn't happen. The only one that should be getting "liked" is the one I click on. How can I fix this?
CommentAdapter
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Comment comment = mCommentList.get(position);
holder.comment.setText(comment.getComment());
commentLike(comment.getCommentid(), holder.commentLike);
commentDislike(comment.getCommentid(), holder.commentDislike);
holder.commentLike.setOnClickListener(v -> {
if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("dislike")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
} else if (holder.commentLike.getTag().equals("like") && holder.commentDislike.getTag().equals("disliked")) {
likeComment(comment.getCommentid(), mPostId, comment.getPublisher());
removeDislike(comment.getCommentid());
} else {
removeLike(comment.getPublisher(), comment.getCommentid());
}
});
holder.commentDislike.setOnClickListener(v -> {
if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("like")) {
dislikeComment(comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else if (holder.commentDislike.getTag().equals("dislike") && holder.commentLike.getTag().equals("liked")) {
dislikeComment(comment.getCommentid());
removeLike(comment.getPublisher(), comment.getCommentid());
Toast.makeText(mContext, "Don't be mean", Toast.LENGTH_SHORT).show();
} else {
removeDislike(comment.getCommentid());
}
});
holder.itemView.setOnLongClickListener(v -> {
if (comment.getPublisher().equals(mFirebaseUser.getUid())) {
AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
alertDialog.setTitle("Would you like to delete this comment?");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "No", (dialog, which) -> dialog.dismiss());
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", (dialog, which) -> {
deleteCommentNotification(mPostId, comment.getCommentid());
FirebaseDatabase.getInstance().getReference("Comments Liked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Comments Disliked").child(comment.getCommentid()).setValue(null);
FirebaseDatabase.getInstance().getReference("Responses").child(comment.getCommentid()).setValue(null);
Toast.makeText(mContext, "Your comment has been deleted.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
});
alertDialog.show();
}
return true;
});
static class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image_profile;
TextView username, comment, commentLikesNumber, commentDislikesNumber, commentResponseNumber, timestamp;
ImageView commentLike, commentDislike, iconComment;
ViewHolder(#NonNull View itemView) {
super(itemView);
commentLike = itemView.findViewById(R.id.icon_thumb_up_grey);
commentDislike = itemView.findViewById(R.id.icon_thumb_down_grey);
}
}
private void commentLike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Liked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_up_blue);
imageView.setTag("liked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_up_grey);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void commentDislike(final String commentid, final ImageView imageView) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments Disliked").child(commentid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mFirebaseUser != null)
if (dataSnapshot.child(mFirebaseUser.getUid()).exists()) {
imageView.setImageResource(R.drawable.ic_thumb_down_blue);
imageView.setTag("disliked");
} else {
imageView.setImageResource(R.drawable.ic_thumb_down_grey);
imageView.setTag("dislike");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
CommentsActivity
private void readComments() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Comments").child(mPostId);
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Comment comment = dataSnapshot.getValue(Comment.class);
try {
comment.setComment(decrypt(comment.getComment(), mPassword));
} catch (Exception e) {
e.printStackTrace();
}
mCommentList.add(comment);
keysList.add(dataSnapshot.getKey());
mCommentAdapter.notifyItemInserted(mCommentList.size() - 1);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = keysList.indexOf(dataSnapshot.getKey());
mCommentList.remove(index);
keysList.remove(index);
mCommentAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
reference.addChildEventListener(childEventListener);
}
I have seen your code and found that you are making mistake by fetching data from firebase by creating methods in the adapter and calling it from onBindViewHolder.
I am currently working with firebase realtime database and I had faced the same problem like you before 3 months and the solution i have used is working fine.
You should have to use asyncTask inside recycler view adapter. Please have a look at my code, this may help you.
Feel free to ask me if you need any help regarding android and firebase
ChooserAdapter.java
public class ChooserAdapter extends RecyclerView.Adapter<ViewHolder> {
ArrayList<Bean> list;
Context context;
public ChooserAdapter(ArrayList<DoctorList> list, Context context) {
this.listFiltered = list;
this.list = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.bean = list.get(position);
holder.asyncTask = new AsyncTask(holder,holder.bean.getId());
holder.asyncTask.execute();
}
#Override
public int getItemCount() {
return list.size();
}
public ArrayList<List> adapterList() {
return list;
}
public List getItem(int position) {
return list.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txtTitle)
TextView txtTitle;
AsyncTask asyncTask;
Bean bean;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
static class AsyncTask extends AsyncTask<Void, Integer, String> {
ViewHolder viewHolder;
String Id;
DatabaseReference dbRef;
AsyncTask(ViewHolder viewHolder, String Id) {
this.viewHolder = viewHolder;
this.Id = Id;
dbRef = FirebaseDatabase.getInstance().getReference("FcmNode");
dbRef.keepSynced(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
if (!isCancelled())
dbRef.orderByChild("Id").equalTo(Id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String name = dataSnapshot.getValue(String.class);
viewHolder.txtTitle.setText(name);
viewHolder.txtTitle.setVisibility(View.VISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return "";
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
}
}
}
I am trying to remove duplicate values from an ArrayList using HashSet, so that city names aren't returned more than once if they are the same… The List comes back either empty or still shows duplicate values. Was hoping someone could tell me where the error is in my code, so that no duplicate values are returned...
I am using this for reference:
Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set); , but can't figure out how to make it work in my code. Know it's probably a simple fix, but I've been playing around with it and still hasn't come back right...
Anyone can tell me where I am going wrong here? According to everyone so far the code looks like it should be working... Although it's not...
SearchCityFragment
public class SearchCityFragment extends Fragment {
private List<Post> mPostList;
private Set<Post> mPostSet;
private RecyclerView mRecyclerView;
private CityAdapter mCityAdapter;
private EditText mSearchBar;
private RelativeLayout mRelativeLayout;
private Activity mActivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search_city, container, false);
mRelativeLayout = view.findViewById(R.id.relative_layout_11);
mRelativeLayout.setVisibility(View.VISIBLE);
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(linearLayoutManager);
mPostList = new ArrayList<>();
mCityAdapter = new CityAdapter(getContext(), mPostList);
mRecyclerView.setAdapter(mCityAdapter);
mSearchBar = mActivity.findViewById(R.id.search_bar);
mSearchBar.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) {
searchCity(s.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
private void searchCity(String s) {
Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("city").startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mPostList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
if (s.length() == 0) {
mPostList.clear();
mRelativeLayout.setVisibility(View.VISIBLE);
} else {
mRelativeLayout.setVisibility(View.GONE);
mPostList.add(post);
mPostSet = new HashSet<>(mPostList);
mPostList.clear();
mPostList.addAll(mPostSet);
readCity();
}
}
mCityAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readCity() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (mSearchBar.getText().toString().equals("")) {
mPostList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
mPostList.add(post);
mPostSet = new HashSet<>(mPostList);
mPostList.clear();
mPostList.addAll(mPostSet);
}
mCityAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
if (context instanceof Activity) {
mActivity = (Activity) context;
}
}
}
if you only want to show the post with searched city and you want to show only one such post you can just query the database for post with that city , you don't need to create any arraylist or hashmap.
private void searchCity(String s) {
FirebaseDatabase.getInstance()
.getReference("Posts")
.orderByChild("city")
.startAt(s)
.limitToFirst(1).
.addValueEventListener(new ValueEvnetListener){
#Override
public void onDataChange(DataSnapshot
dataSnapshot) {
// do your rhing
}
#Override
public void onCancelled(DatabaseError databaseError) {}
} ;
}
So i have a recycler view that is designed to show users sending messages to each other from my Firebase RTD. Originally it was working to show all users and the recycler items were clicked then it would show messages between the users. However, when modifying it to only view users that were in open messages with the current user, the items that populated my recycler view no longer displays and an error saying E/RecyclerView: No adapter attached; skipping layout is logged within the Run tab.
Unfortunately i can no longer undo the changes and have struggled to find the cause of my problem but have assume that it is either taking place in my adapted or activity classes.
InboxActivity.java:
public class InboxActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<User> inboxLst;
FirebaseUser user;
DatabaseReference reference;
UserAdapter usrAdpt;
private List<String> userLst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inbox);
//Identify and setup recycler view
recyclerView = findViewById(R.id.rycInbox);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userLst = new ArrayList<>();
//Get all chats between current user and and other users
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear();
for (DataSnapshot snp : dataSnapshot.getChildren()){
Chat chat = snp.getValue(Chat.class);
if (chat.getSender().equals(user.getUid())){
userLst.add(chat.getReceiver());
}
if (chat.getReceiver().equals(user.getUid())){
userLst.add(chat.getSender());
}
}
readChat();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readChat() {
inboxLst = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear();
for (DataSnapshot snp : dataSnapshot.getChildren()) {
User usr = snp.getValue(User.class);
//Display users that are currently in an open chat
for (String id : userLst){
if(usr.getId().equals(id)){
if(inboxLst.size() != 0){
for (User usrl : inboxLst){
if(!usr.getId().equals(usrl.getId())){
inboxLst.add(usr);
}
}
}else{
inboxLst.add(usr);
}
}
}
}
//Set the adapter for the recycler view once using the chat information retrieved from firebase database
usrAdpt = new UserAdapter(InboxActivity.this,inboxLst);
recyclerView.setAdapter(usrAdpt);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
}
UserAdapter.java:
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context cont;
private List<User> nUser;
public UserAdapter(Context cont, List<User> nUser){
this.cont = cont;
this.nUser = nUser;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(cont).inflate(R.layout.lst_layout_inbox, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = nUser.get(position);
holder.username.setText(user.getUsername());
holder.usrLst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(cont, MessageActivity.class);
intent.putExtra("userid",user.getId());
cont.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return nUser.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
RelativeLayout usrLst;
public ViewHolder(View itemView){
super(itemView);
username = itemView.findViewById(R.id.usrName);
usrLst = itemView.findViewById(R.id.usrCard);
}
}
}
The only catchup in your question is, in the following method:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userLst.clear(); // <------ WHY YOU CLEAR LIST HERE??? COMMENT THIS ----------
for (DataSnapshot snp : dataSnapshot.getChildren()) {
User usr = snp.getValue(User.class);
//Display users that are currently in an open chat
for (String id : userLst){
if(usr.getId().equals(id)){
if(inboxLst.size() != 0){
for (User usrl : inboxLst){
if(!usr.getId().equals(usrl.getId())){
inboxLst.add(usr);
}
}
}else{
inboxLst.add(usr);
}
}
}
}
//Set the adapter for the recycler view once using the chat information retrieved from firebase database
usrAdpt = new UserAdapter(InboxActivity.this,inboxLst);
recyclerView.setAdapter(usrAdpt);
}
why you do userLst.clear(); ?
Since in OnCreate() method you populate userLst and call readChat(). And in onDataChange() you clear the userLst and then afterwards you try to iterate over the userLst to Display users that are currently in an open chat.
I would suggest to comment this userLst.clear(); and after setting items call notifyDataSetChanged()
Try these things:
Set the adapter in onCreate.
and in the onDataChanged listener, update the ArrayList and call notifyDataSetChanged().
This should help
I'm trying to remove data from my recyclerview and let it be updated in the mobile ui as well. It is an android app. I am able to delete the data alright but I always have to leave that page and come back when I make the changes. I tried making some modifications to the onChildRemoved method but I started getting crashes upon making this change. What do I do? Below is my code.
MainActivity.java
DatabaseReference databaseReference;
List<DataSnapshot> listData;
RecyclerView recyclerView;
MyCart.MyAdapter adapter;
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new MyCart.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
private void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference()
.child("Customers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Items students = dataSnapshot.getValue(Items.class);
listData.add(dataSnapshot);
recyclerView.setAdapter(adapter);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Adapter Class
public class MyAdapter extends RecyclerView.Adapter<MyCart.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(MyCart.MyAdapter.ViewHolder holder, int position) {
final DataSnapshot studentSnapshot = list.get(position);
final Items students = studentSnapshot.getValue(Items.class);
final String list_user_id = studentSnapshot.getKey();
holder.item_name.setText(students.getItem_name());
holder.item_price.setText(students.getItem_price());
Picasso.with(holder.item_image.getContext()).load(students.getItem_image()).placeholder(R.drawable.no_image_two).into(holder.item_image);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
adapter.notifyDataSetChanged();
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public MyCart.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_item_layout, parent, false);
return new MyCart.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView item_name, item_price;
ImageView item_image;
ImageView delete;
public ViewHolder(View itemView) {
super(itemView);
item_name = itemView.findViewById(R.id.item_name);
item_price = itemView.findViewById(R.id.item_price);
item_image = itemView.findViewById(R.id.item_image);
delete = itemView.findViewById(R.id.delete_item);
}
}
#Override
public int getItemCount() {
return list.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference prod_ref = FirebaseDatabase.getInstance().getReference().child("Customers").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("My Cart").child(list_user_id);
prod_ref.removeValue();
//add/modify these two lines here
list.remove(position);
notifyDataSetChanged();
}
});
And one more change you need to do
// move this toast to onChildRemoved method and clear the other code from there
Toast.makeText(MyCart.this, "Item removed from cart", Toast.LENGTH_SHORT).show();
like
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
//remove these line these will raise the exception and Toast here
int index = listData.indexOf(dataSnapshot);
listData.remove(index);
adapter.notifyDataSetChanged();
}
When dataSnapshot does not exist in list, it returns -1. Index of list start from 0. Therefore, you're this getting error. You need to add a guard check here like:
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
int index = listData.indexOf(dataSnapshot);
if(index > 0) {
listData.remove(index);
}
adapter.notifyDataSetChanged();
}
This is my firebase structure
databaseSupp.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
suppList.clear();
for (DataSnapshot suppSnapshot : dataSnapshot.child("Task").getChildren()) {
//Log.d("fbBee", dataSnapshot.getRef().child("Task").child("9223450").child("Firebase").toString());
Log.d("fbBee", suppSnapshot.getValue().toString());
Log.d("fbGet",suppSnapshot.child("Firebase").getValue().toString());
Supp supp = suppSnapshot.child("Firebase").getValue(Supp.class);
suppList.add(supp);
}
SuppList adapter = new SuppList(MainActivity2.this, suppList);
mListViewSupp.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
This is my code, but this code just show child Firebase. I want read and show data from child Firebase, but I need flag on child Reply for reference in my fragmens. please help for code.
Try something like that:
final DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Task/");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot taskNo : dataSnapshot.getChildren()) {
// now you in (9223450)
Object firebaseObj = taskNo.child("Firebase").getValue(FirebaseObj.class); //class with params set/get methods
Object replayObj = taskNo.child("Replay").getValue(ReplayObj.class); //class with params set/get methods
// ALTERNATIVE
/*
for (DataSnapshot child : taskNo.getChildren()) {
if(child.getKey().equals("Firebase")) {
String address = child.child("Address").getValue(String.class);
String customer = child.child("Customer").getValue(String.class);
// ...
} else if (child.getKey().equals("Replay")) {
// replay
// ...
}
}
*/
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
Like This
public class SuppList extends ArrayAdapter {
private Activity context;
private List<Supp> suppList;
public SuppList (Activity context, List<Supp> suppList){
super(context, R.layout.list_layout_new, suppList);
this.context = context;
this.suppList = suppList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout_new, null, true);
TextView textViewSo = (TextView) listViewItem.findViewById(R.id.textViewSo);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewAddress = (TextView) listViewItem.findViewById(R.id.textViewAddress);
Supp supp = suppList.get(position);
textViewSo.setText(supp.getSuppId());
//Log.e("SuppTest", supp.getSuppId());
textViewName.setText(supp.getSuppName());
textViewAddress.setText(supp.getSuppAddress());
return listViewItem;
}
}