RecyclerView duplicates other items after deleting an item.
Tried to clear ArrayList but it's not working
I'm a newbie so some information got from the internet.
Also in the firebase item deleting multiple times.
please help me
There's my code and firebase picture:
Adapter
public class MovieFavAdapter extends RecyclerView.Adapter<FavViewHolder> {
private Activity activity;
private List<MovieDetail> results;
int id;
FirebaseAuth auth;
String uid;
private ImageView deleteItem;
DatabaseReference db;
MovieDetail result;
FavViewHolder favViewHolder;
int i;
Intent intent;
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
public MovieFavAdapter(Activity activity, List<MovieDetail> results) {
this.activity = activity;
this.results = results;
}
#NonNull
#Override
public FavViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(activity.getApplicationContext()).inflate(R.layout.fav_items,parent, false);
favViewHolder = new FavViewHolder(view);
return favViewHolder;
}
#Override
public void onBindViewHolder(#NonNull FavViewHolder holder, #SuppressLint("RecyclerView") int position) {
result = results.get(position);
auth = FirebaseAuth.getInstance();
holder.setPosterImageView(activity, result.getPoster_path());
String title = result.getTitle();
holder.poster_title_movie.setText(title);
i = holder.getAdapterPosition();
if (title != null) {
holder.poster_title_movie.setVisibility(View.VISIBLE);
holder.poster_title_movie.setText(title);
} else {
holder.poster_title_movie.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
id = result.getId();
Intent intent = new Intent(view.getContext(), MovieDetailActivity.class);
intent.putExtra("id", String.valueOf(id));
activity.startActivity(intent);
activity.onBackPressed();
}
});
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
id = results.get(i).getId();
uid = auth.getCurrentUser().getUid();
db = FirebaseDatabase.getInstance().getReference();
db.child("MovieId").child(uid).child(String.valueOf(id)).removeValue();
results.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, results.size());
Toast.makeText(activity.getApplicationContext(), "Delete "+ i, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return results.size();
}
}
Fragment
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
databaseReference = FirebaseDatabase.getInstance().getReference("MovieId");
results=new ArrayList<>();
auth = FirebaseAuth.getInstance();
uid = auth.getUid();
retrofitService = RetrofitClient.getClient().create(RetrofitService.class);
if (!results.isEmpty()){
results.clear();
}
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fav_movie_layout, container, false);
favRecycler = v.findViewById(R.id.fav_movie_list);
favRecycler.setHasFixedSize(true);
favRecycler.setItemAnimator(null);
favRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
movieFavAdapter = new MovieFavAdapter(getActivity(), results);
movieFavAdapter.notifyDataSetChanged();
movieFavAdapter.setHasStableIds(true);
databaseReference.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
results.clear();
Call<MovieDetail> movieDetailCall = retrofitService.getMovieDetailsById(Integer.parseInt(dataSnapshot.getKey()), BuildConfig.Api_Key);
movieDetailCall.enqueue(new Callback<MovieDetail>() {
#Override
public void onResponse(Call<MovieDetail> call, Response<MovieDetail> response) {
MovieDetail movieDetail = response.body();
results.add(movieDetail);
movieFavAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<MovieDetail> call, Throwable t) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
favRecycler.setAdapter(movieFavAdapter);
return v;
}
}
Firebase
enter image description here
Related
I am making an application in which products are inserted into the database and I am inserting the 1 product once. it is working fine. But when I delete a specific node/ product from Database. deletion code is also working fine but at the same time product is again adding into the database.
Main Fragment Code;
public class Products_fragment extends Fragment {
FloatingActionButton fab_addproduct;
RecyclerView recyclerView;
EditText searchview;
BottomSheetDialog bottomSheetDialog;
FirebaseDatabase firebaseDatabase;
ArrayList<Product_model> DatabaseProductlist;
FirebaseAuth auth;
CircularDotsLoader ProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_products_fragment, container, false);
setviews(view);
setInitilization();
setclicks();
setadapter();
return view;
}
private void setInitilization() {
DatabaseProductlist = new ArrayList<>();
}
private void setadapter() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
DatabaseReference reference = database.getReference("Users").child(UID).child("Products");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ProgressBar.setVisibility(View.GONE);
DatabaseProductlist.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Product_model model = dataSnapshot.getValue(Product_model.class);
DatabaseProductlist.add(model);
}
Product_Adapter product_adapter = new Product_Adapter(DatabaseProductlist);
recyclerView.setAdapter(product_adapter);
product_adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(), error.getMessage());
}
});
}
private void setclicks() {
fab_addproduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog = new BottomSheetDialog(getContext(), R.style.AppBottomSheetDialogTheme);
bottomSheetDialog.setContentView(R.layout.productadd_bottom_sheet);
TextInputEditText product_id = bottomSheetDialog.findViewById(R.id.product_id);
TextInputEditText product_name = bottomSheetDialog.findViewById(R.id.product_name);
TextInputEditText product_quantity = bottomSheetDialog.findViewById(R.id.product_quantity);
MaterialButton add_btn = bottomSheetDialog.findViewById(R.id.add_btn);
TextInputEditText product_price = bottomSheetDialog.findViewById(R.id.product_price);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(product_name.getText()).toString().isEmpty() || product_id.getText().toString().isEmpty() || product_price.getText().toString().isEmpty() || product_quantity.getText().toString().isEmpty()) {
ToastUtility.showErrorToast(getContext(), "Please Fill all Fields");
} else {
Product_model model = new Product_model(Integer.parseInt(product_id.getText().toString()), Integer.parseInt(product_quantity.getText().toString()), Integer.parseInt(product_price.getText().toString()), product_name.getText().toString());
firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference("Users");
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentFirebaseUser != null;
String UID = currentFirebaseUser.getUid();
reference.child(UID).child("Products").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(product_name.getText().toString().trim()).exists()) {
ToastUtility.showErrorToast(getContext(),"Product Already Exists!");
}
else{
reference.child(UID).child("Products").child(product_name.getText().toString().trim()).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
ToastUtility.showSuccessToast(getContext(),"Successfully Added");
setadapter();
}
else{
ToastUtility.showErrorToast(getContext(), Objects.requireNonNull(task.getException()).getMessage());
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
ToastUtility.showErrorToast(getContext(),error.getMessage());
}
});
}
}
});
bottomSheetDialog.show();
}
});
}
private void setviews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
fab_addproduct = view.findViewById(R.id.fab_addproduct);
searchview = view.findViewById(R.id.searchview);
ProgressBar = view.findViewById(R.id.progressbar);
}
}
Adapter Code:
public class Product_Adapter extends RecyclerView.Adapter<Product_Adapter.myviewholder> {
ArrayList<Product_model> dataholder;
public Product_Adapter(ArrayList<Product_model> dataholder) {
this.dataholder = dataholder;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow_product, parent, false);
return new myviewholder(view); }
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.idtv.setText("" + dataholder.get(position).getId());
holder.pnametv.setText("" + dataholder.get(position).getProduct_name());
holder.pqtytv.setText("" + dataholder.get(position).getProduct_quantity());
holder.ppritv.setText("" + dataholder.get(position).getProduct_price());
holder.delimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
FirebaseUser curUser = FirebaseAuth.getInstance().getCurrentUser();
assert curUser != null;
String UID = curUser.getUid();
String productname = dataholder.get(holder.getAdapterPosition()).getProduct_name();
DatabaseReference reference = db.getReference("Users").child(UID).child("Products");
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
notifyItemRemoved(holder.getAdapterPosition());
}
else
{
ToastUtility.showErrorToast(view.getContext(),"Product is not deleting ");
}
}
});
}
});
}
#Override
public int getItemCount() {
return dataholder.size();
}
static class myviewholder extends RecyclerView.ViewHolder{
TextView idtv, pnametv, pqtytv, ppritv, delimg, edit_img;
public myviewholder(#NonNull View itemView) {
super(itemView);
idtv = itemView.findViewById(R.id.idtv);
pnametv = itemView.findViewById(R.id.pnametv);
pqtytv = itemView.findViewById(R.id.pqtytv);
ppritv = itemView.findViewById(R.id.ppritv);
delimg = itemView.findViewById(R.id.delimg);
edit_img = itemView.findViewById(R.id.edit_img);
}
}
}
When you click delete, shouldn't you remove your item from the list before notifying data changed:
//this code belongs to the part where you click the delete
.........
reference.child(productname).setValue(null).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
ToastUtility.showSuccessToast(view.getContext(),"Suucessfully Deleted");
//here remove the item from your list
dataholder.remove(holder.getAdapterPosition());
//then notify the adapter
notifyItemRemoved(holder.getAdapterPosition());
}
It is like social media app,This fragment should display the chat list, But it isn't, Here is the codes:
DirectMessagesFragment:
public class DirectMessagesFragment extends Fragment{
FirebaseAuth firebaseAuth;
FirebaseUser currentUser;
AdapterChatlist adapterChatlist;
DatabaseReference ref;
RecyclerView recyclerViewChatter;
List<ModelChatter> chatterList ;
List<ModelChatlist> chatlistList ;
public DirectMessagesFragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_direct_messages, container, false);
firebaseAuth = FirebaseAuth.getInstance();
currentUser = FirebaseAuth.getInstance().getCurrentUser();
recyclerViewChatter = view.findViewById(R.id.chatter_recyclerview);
chatlistList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Chatlist").child(currentUser.getUid());
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatlistList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);}
loadChats();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
return view;
}
private void loadChats() {
chatterList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chatterList.clear();
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatter chatter = ds.getValue(ModelChatter.class);
for(ModelChatlist chatlist: chatlistList){
if(chatter.getUid() != null && chatter.getUid().equals(chatlist.getId())){
chatterList.add(chatter);
break;
}}
adapterChatlist = new AdapterChatlist(getContext(), chatterList);
recyclerViewChatter.setAdapter(adapterChatlist);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}}
In ChatActivity:
//create chat list in firebase
DatabaseReference ref1 =
FirebaseDatabase.getInstance().getReference("ChatList")
.child(uid).child(hisUid);
ref1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref1.child("id").setValue(hisUid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("ChatList")
.child(hisUid).child(uid);
ref2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!snapshot.exists()){
ref2.child("id").setValue(uid);
}}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});}
#Override
public void afterTextChanged(Editable s) {
}
};
/////////
}
ModelChatlist only contain id.
ModelChatter contain name, image, uid.
AdapterChatlist:
public class AdapterChatlist extends RecyclerView.Adapter<AdapterChatlist.MyHolder>{
Context context;
List<ModelChatter> chattersList;
public AdapterChatlist(Context context, List<ModelChatter> chattersList) {
this.context = context;
this.chattersList = chattersList;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_dm, parent, false);
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
String userImage = chattersList.get(position).getImage();
String userName = chattersList.get(position).getName();
String hisUid = chattersList.get(position).getUid();
holder.chatter_name.setText(userName);
try {
Picasso.with(context).load(userImage).placeholder(R.drawable.user).into(holder.chatter_img);
} catch (Exception e){
Picasso.with(context).load(R.drawable.user).into(holder.chatter_img);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra("hisUid", hisUid);
context.startActivity(intent);
}
});}
#Override
public int getItemCount() {
return chattersList.size();}
class MyHolder extends RecyclerView.ViewHolder{
ImageView chatter_img;
TextView chatter_name;
public MyHolder(#NonNull View itemView) {
super(itemView);
chatter_img = itemView.findViewById(R.id.chatter_img);
chatter_name = itemView.findViewById(R.id.chatter_name);
}}}}
fragment_direct_messages layout contain the recyclerview, row_dm contain the cardview
Any help will be appreciated..
Pass chat list into your method
for (DataSnapshot ds:snapshot.getChildren()){
ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
chatlistList.add(chatlist);
}
loadChats(chatlistList);
private void loadChats(List<ModelChatlist> chatlist) {
//your code
}
Try adding filters (like logging the data received) to check where the actual problem persists. It's difficult to go through so much code.
I want to open one fragment from another. But as the result I get this (two mixed fragments):
Here is code of the fragment from which I want to go to the next fragment:
public class ChatRoomFragment extends Fragment implements View.OnClickListener in l1.setOnItemClickListener {
DatabaseReference reference;
static HashMap<String, String> dataHashMap = new HashMap<String, String>();
ArrayList<String> arrayList;
EditText e1;
ListView l1;
ArrayAdapter<String> adapter;
String name;
EditText ee;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chatroom_fragment, container, false);
Button button = view.findViewById(R.id.button);
button.setOnClickListener(this);
super.onCreate(savedInstanceState);
e1 = (EditText)view.findViewById(R.id.editText);
l1 = (ListView)view.findViewById(R.id.listView);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,arrayList);
l1.setAdapter(adapter);
FirebaseOptions options = new FirebaseOptions.Builder()
.../setting options
FirebaseApp.initializeApp(getActivity(), options, "secondary");
FirebaseApp app = FirebaseApp.getInstance("secondary");
reference = FirebaseDatabase.getInstance(app).getReference().getRoot();
request_username();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
arrayList.clear();
arrayList.addAll(set);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Toast.makeText(NavigationDrawerActivity.this, "No network connectivity", Toast.LENGTH_SHORT).show();
}
});
ChatFragment fragment = new ChatFragment();
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
dataHashMap.put("room_name", ((TextView) view).getText().toString());
dataHashMap.put("user_name", name);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
});
return view;
}
public void request_username()
{
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Enter your name?");
ee = new EditText(getActivity());
builder.setView(ee);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = ee.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_username();
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
insert_data(v);
break;
}
}
public void insert_data(View v)
{
switch (v.getId()) {
case R.id.button :
Map<String, Object> map = new HashMap<>();
map.put(e1.getText().toString(), "");
reference.updateChildren(map);
}
}
}
Here is the code of the Fragment to which I want to go:
EditText e1;
TextView t1;
private String user_name,room_name;
DatabaseReference reference;
String temp_key;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chat_fragment, container, false);
Button button = view.findViewById(R.id.button2);
button.setOnClickListener(this);
super.onCreate(savedInstanceState);
e1= view.findViewById(R.id.editText2);
t1= view.findViewById(R.id.textView);
if(((AppCompatActivity)getActivity()).getSupportActionBar()!=null)
{
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Log.d("checkintent", getActivity().getIntent().toString());
//user_name = getActivity().getIntent().getExtras().get("user_name").toString();
user_name = ChatRoomFragment.dataHashMap.get("user_name").toString();
//room_name = getActivity().getIntent().getExtras().get("room_name").toString();
room_name = ChatRoomFragment.dataHashMap.get("room_name").toString();
FirebaseApp app = FirebaseApp.getInstance("secondary");
reference = FirebaseDatabase.getInstance(app).getReference().getRoot();
getActivity().setTitle(" Room - "+room_name);
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
append_chat(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
getActivity().finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
send(v);
break;
}
}
public void send(View v)
{
Map<String,Object> map = new HashMap<String,Object>();
temp_key = reference.push().getKey();
reference.updateChildren(map);
DatabaseReference child_ref = reference.child(temp_key);
Map<String,Object> map2 = new HashMap<>();
map2.put("name",user_name);
map2.put("msg", e1.getText().toString());
child_ref.updateChildren(map2).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
e1.setText("");
}
public void append_chat(DataSnapshot ss)
{
String chat_msg,chat_username;
Iterator i = ss.getChildren().iterator();
while(i.hasNext())
{
chat_msg = ((DataSnapshot)i.next()).getValue().toString();
chat_username = ((DataSnapshot)i.next()).getValue().toString();
t1.append(chat_username + ": " +chat_msg + " \n");
}
}
}
What should I change to have the ChatFragment opened only, but not both fragments at the same time? (I need pink items to be on the screen only)
When I run the activity it shows me items that I want plus a null card view(when i delete tostring() from holder.setTitle("product name:"+model.getName().toString()); I'm trying so hard to solve this problem but I didn't find a solution.
this is my class Client_order:
public class Client_order extends AppCompatActivity {
FragmentManager fragmentManager;
Fragment Settingsfrag,Orderfrag,panierfrag;
TextView delorder;
Order model2;
Button submit;
DatabaseReference ref,ref1,ref2;
private Toolbar hometoolbar;
private ImageView settingsbtn, orderIV, imageView7,imageView10;
private RecyclerView orderrv;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private DatabaseReference mDatabase;
private String user_id;
Spinner spinnerorder;
private String name;
private String email;
private String phone;
TextView tvName;
Orderviewholder holder1;
private FirebaseRecyclerAdapter<Order, Orderviewholder> orderAdapter;
DatabaseReference dborder,dbpanier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_order);
tvName = findViewById(R.id.tvName);
hometoolbar = findViewById(R.id.hometoolbarorder);
hometoolbar.setTitle("ordre");
hometoolbar.setTitleTextColor(Color.WHITE);
settingsbtn = findViewById(R.id.settingsbtn);
orderIV = findViewById(R.id.orderIV);
imageView7 = findViewById(R.id.imageView7);
fragmentManager=getSupportFragmentManager();
Orderfrag=fragmentManager.findFragmentById(R.id.orderfrag);
Settingsfrag=fragmentManager.findFragmentById(R.id.settingsfrag);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
if (currentUser == null) {
Intent intent=new Intent(Client_order.this,Login.class);
startActivity(intent);
} else {
if (!mAuth.getCurrentUser().isEmailVerified()) {
Toast.makeText(getApplicationContext(), "Please verify your email address", Toast.LENGTH_LONG).show();
Intent startActivity = new Intent(this, Login.class);
startActivity(startActivity);
finish();
} else {
user_id = currentUser.getUid();
}
}
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_LONG).show();
panierfrag=fragmentManager.findFragmentById(R.id.panierfrag);
submit=findViewById(R.id.submit);
submit.setVisibility(View.VISIBLE);
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
imageView7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(Client_order.this,Client_panier.class);
startActivity(intent);
}
});
settingsbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.hide(Orderfrag)
.show(Settingsfrag)
.commit();
}
});
orderIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager.beginTransaction()
.hide(panierfrag)
.show(Orderfrag)
.hide(Settingsfrag)
.commit();
}
});
dborder = FirebaseDatabase.getInstance().getReference().child("order");
dborder.keepSynced(true);
orderrv = (RecyclerView) findViewById(R.id.orderrv);
DatabaseReference personsRef = FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
Query personsQuery = personsRef.orderByKey();
orderrv.hasFixedSize();
orderrv.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions personsOptions = new FirebaseRecyclerOptions.Builder<Order>().setQuery(personsQuery, Order.class).build();
orderAdapter=new FirebaseRecyclerAdapter<Order, Orderviewholder>(personsOptions) {
#Override
protected void onBindViewHolder(#NotNull Orderviewholder holder, int position, #NotNull Order model) {
holder.setTitle("product name:"+model.getName().toString());
holder1=holder;
imageView10=holder.mView.findViewById(R.id.imageVieworder);
Picasso.get().load(model.getImage()).into(imageView10, new Callback() {
#Override
public void onSuccess() {
ProgressBar progressbar3;
progressbar3=holder1.mView.findViewById(R.id.progressBar4);
progressbar3.setVisibility(View.INVISIBLE);
}
#Override
public void onError(Exception e) {
}
});
holder.setdesc(model.getDesc().toString());
holder.setprice(model.getPrice());
holder.setquantity(model.getQuantity());
TextView status;
status=holder.mView.findViewById(R.id.statusorder);
status.setText(model.getStatus());
status.setVisibility(View.VISIBLE);
delorder=holder.mView.findViewById(R.id.orderDelbtn);
delorder.setText("done");
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delorder.setVisibility(View.VISIBLE);
}
});
model2=model;
delorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dborder.child(currentUser.getUid()).child(model2.getId()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NotNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Client_order.this, "order deleted successfully", Toast.LENGTH_LONG).show();
}
}
});
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ref=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString());
ref2=FirebaseDatabase.getInstance().getReference().child("order").child(user_id.toString()).child("submitted");
ref1=FirebaseDatabase.getInstance().getReference().child("order").child("admin");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NotNull DataSnapshot dataSnapshot) {
for (DataSnapshot orderSnapshot: dataSnapshot.getChildren()) {
Order category = orderSnapshot.getValue(Order.class);
//if (category!=null){
ref1.child(category.getId()).setValue(category);
Toast.makeText(Client_order.this,"product successfully submitted", Toast.LENGTH_LONG).show();
ref2.child(category.getId()).setValue(category);
ref.child(category.getId()).removeValue();
// }
}
}
#Override
public void onCancelled(#NotNull DatabaseError databaseError) {
}
});
}
});
}
#NotNull
#Override
public Orderviewholder onCreateViewHolder(#NotNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_list_itemorder, parent, false);
return new Orderviewholder(view);
}
};
orderrv.setAdapter(orderAdapter);
}
#Override
protected void onStart() {
super.onStart();
orderAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
orderAdapter.stopListening();
}
public static class Orderviewholder extends RecyclerView.ViewHolder{
View mView;
public Orderviewholder(View itemView){
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView)mView.findViewById(R.id.order_name);
post_title.setText(title);
}
public void setdesc(String desc) {
TextView post_title = (TextView) mView.findViewById(R.id.order_description);
post_title.setText(desc);
}
public void setprice(int price) {
TextView post_title = (TextView) mView.findViewById(R.id.order_price);
post_title.setText(Integer.toString(price)+" dhs");
}
public void setquantity(int quantity) {
TextView post_title = (TextView) mView.findViewById(R.id.order_quantity);
post_title.setText(Integer.toString(quantity));
}
}
}
it shows me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:207)
at com.omar.lazywork.Client_order$4.onBindViewHolder(Client_order.java:204)
I've created a match system in my Android program that also includes a chat section which has 2 fragments. The first fragment shows your chats, the second one shows your matches by using RecyclerView and UsersAdapter. However, in the second (match) fragment, people who you matched with are shown many times. For example, the same person is seen many times as you can see here.
My code is below.
UserFragment:
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UsersAdapter usersAdapter;
private List<User> mUsers;
FirebaseFirestore usersfragmentstore;
FirebaseAuth readauth;
DocumentReference readref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
usersfragmentstore = FirebaseFirestore.getInstance();
readauth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_users, container, false);
readref = usersfragmentstore.collection("users").document(readauth.getCurrentUser().getUid());
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return view;
}
}
UserAdapter:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
String theLastMessage;
public UsersAdapter(Context mContext, List<User> mUsers, boolean ischat) {
this.mUsers = mUsers;
this.mContext = mContext;
this.ischat = ischat;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item_chat, parent, false);
return new UsersAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = mUsers.get(position);
holder.username.setText(user.getName());
if (user.getImageURL().equals("default")) {
holder.profile_image.setImageResource(R.drawable.profilepicture);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat) {
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat) {
if (user.getStatus().equals("online")) {
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username = itemView.findViewById(R.id.chatusername);
profile_image = itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg = itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg) {
theLastMessage = "defalut";
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("No message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
What am I missing?
befor adding new data first clear list by mUsers.clear(); as below
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
readref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
DocumentSnapshot shot = task.getResult();
List<String> matchedid2 = new ArrayList<>();
matchedid2 = (List<String>) shot.get("matchlist");
if (matchedid2.contains(snapshot.getKey())) {
mUsers.clear();
User user = snapshot.getValue(User.class);
mUsers.add(user);
usersAdapter = new UsersAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(usersAdapter);
}
}
});
}