here is the error I want to delete data from firebase using .removeValue(); but can't fetch the key inside child using .child(getRef(position).getKey()); it says "Cannot resolve method 'getRef(int)'"
I tried to get the key using getter & setter in model class, but that too didn't work!
Android Studio it does not resolve getRef(int) method. Here is the code:
public class RecyclerContactAdapter extends RecyclerView.Adapter<RecyclerContactAdapter.ViewHolder> {
Context context;
ArrayList<User> list;
DataSnapshot snapshot;
FirebaseFirestore firestore;
FirebaseAuth auth;
DatabaseReference reference;
//for search
public void setFilteredList(ArrayList<User> filteredList){
this.list = filteredList;
notifyDataSetChanged();
}
public RecyclerContactAdapter(Context context, ArrayList<User>list){
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.contact_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
User user = list.get(position);
// String id1 = list.get(position).getKey();
holder.name.setText(user.getName());
holder.chn.setText(user.getChn());
holder.shn.setText(user.getShn());
holder.phone.setText(user.getPhone());
holder.hostel_optn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase.getInstance().getReference().child("HostelSwappingDatabase")
.child(getRef(position).getKey())
.removeValue();
}
});
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return list.size();
}
//
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
//
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView name, chn, shn, phone;
ImageView hostel_optn;
public ViewHolder(View itemView){
super(itemView);
name = itemView.findViewById(R.id.name);
chn = itemView.findViewById(R.id.chn);
shn = itemView.findViewById(R.id.shn);
phone = itemView.findViewById(R.id.phone);
hostel_optn = itemView.findViewById(R.id.hostel_optn);
}
}
}
To delete any data instance from Firebase, one must implement FirebaseRecyclerAdapter as mentioned here
also get help from this video, if required click here.
Related
I'm creating an app to simply store the records of a tractions and able to see the record.
In IteamListActivity I want to see my records of tractions.
I want to list all the data item in recycle view.
When I click 'View' button in activity_home xml, app crashes.
GitHub Link of the project is Here
Code is
Adapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.viewHolder>{
ArrayList<DataModel> list;
Context context;
public DataAdapter(ArrayList<DataModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(context).inflate(R.layout.data_list_design,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
DataModel model = list.get(position);
holder.sn.setText(model.getSn());
holder.date.setText(model.getDate());
holder.name.setText(model.getName());
holder.weight.setText(model.getWeight());
holder.rate.setText(model.getRate());
holder.total.setText(model.getTotal());
}
#Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView sn,date,name,weight,rate,total;
public viewHolder(#NonNull View itemView) {
super(itemView);
sn = itemView.findViewById(R.id.snTitle);
date = itemView.findViewById(R.id.dateTitle);
name = itemView.findViewById(R.id.nameTitle);
weight = itemView.findViewById(R.id.weightTitle);
rate = itemView.findViewById(R.id.rateTitle);
total = itemView.findViewById(R.id.totalTitle);
}
}
}
HomeActivity
binding.listview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this,ItemListActivity.class );
startActivity(intent);
}
});
ItemListActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityItemListBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
ArrayList<DataModel> list = new ArrayList<>();
list.add(new DataModel(1,"2021-07-29","Potato", 76,50,100));
list.add(new DataModel(2,"2021-07-30","Potato", 106,60,100));
list.add(new DataModel(3,"2021-08-02","Potato", 83,80,100));
list.add(new DataModel(4,"2021-08-03","Potato", 67,90,100));
list.add(new DataModel(5,"2021-08-05","Potato", 70,70,100));
DataAdapter adapter = new DataAdapter(list,this);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
binding.datalistRv.setLayoutManager(linearLayoutManager);
binding.datalistRv.setNestedScrollingEnabled(false);
binding.datalistRv.setAdapter(adapter);
}
Solution is
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
DataModel model = list.get(position);
holder.sn.setText(model.getSn().toString());
holder.date.setText(model.getDate());
holder.name.setText(model.getName());
holder.weight.setText(model.getWeight().toString());
holder.rate.setText(model.getRate().toString());
holder.total.setText(model.getTotal().toString());
}
Reason of crush is model.getSn(), model.getWeight(), model.getRate(), model.getTotal() return Integer and textView.setText() calls public final void setText(#StringRes int resid) which tries to find string by Integers which you provided from your model.
I'm trying to show the selected items in another view and I can't get the key using getRef method. How should I get the key to pass the data? I tried to find similar solutions on StackOverflow but just can't find it...
This is my onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
final String productKey = getRef(position).getKey();
holder.textViewName.setText(uploadCurrent.getName());
//Picasso.with(mContext).load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);
Glide.with(mContext).asBitmap().load(uploadCurrent.getmImageUrl()).into(holder.imageView);
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, SingleProductActivity.class);
i.putExtra("ProductKey", productKey);
mContext.startActivity(i);
}
});
}
And my class where I'm trying to show upload data.
String productKey = getIntent().getStringExtra("ProductKey");
mDatabaseRef.child(productKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String productName = snapshot.child("mName").getValue().toString();
String productDesc = snapshot.child("mDescription").getValue().toString();
String imageUrl = snapshot.child("mImageUrl").getValue().toString();
productDescriptionTxt.setText(productDesc);
singleProductNameTxt.setText(productName);
productPriceTagTxt.setText("100");
Glide.with(mContext).asBitmap().load(imageUrl).into(singleProductImg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Here is my whole adapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private String link;
private DatabaseReference mDatabaseRef;
public ImageAdapter(Context context, List<Upload> uploads) {
this.mContext = context;
this.mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.product_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
final String productKey = getRef(position).getKey();
holder.textViewName.setText(uploadCurrent.getName());
//Picasso.with(mContext).load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);
Glide.with(mContext).asBitmap().load(uploadCurrent.getmImageUrl()).into(holder.imageView);
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, SingleProductActivity.class);
i.putExtra("ProductKey", productKey);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public TextView textViewName;
public ImageView imageView;
private CardView parent;
private View v;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
parent = itemView.findViewById(R.id.parent);
textViewName = itemView.findViewById(R.id.productNameTxt);
imageView = itemView.findViewById(R.id.productImg);
//v označava jedan prikazan item
v = itemView;
}
}
}
As I see, your ImageAdapter class extends RecyclerView.Adapter. That being said, you are getting the following error:
Cannot resolve method 'getRef' in 'ImageAdapter'.
Because the RecyclerView.Adapter class doesn't contain any getRef() method inside it, hence the error. However, FirebaseRecyclerAdapter does. As you can see, the getRef() method is present in the FirebaseRecyclerAdapter class and not in the RecyclerView.Adapter class.
To solve this, you either adapt to the code of the Firebase-UI library, or you keep using the RecyclerView.Adapter and get the "productKey" like so:
Upload uploadCurrent = mUploads.get(position);
String productKey = uploadCurrent.getProductKey();
But this will only work if you have the productKey as a field inside the Upload class. If you don't have it yet, add it and populate it when you add data to the database.
I want to make search data on my app based on Firebase. I've followed instructions on internet how to make search Firebase.
It shows no error, but when I clicked search button, my recycleview is empty, no data showed.
Here is my code:
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String searchText = search_cust.getText().toString();
firebaseCustSearch(searchText);
}
});
This is my firebase search method
private void firebaseCustSearch(String searchText) {
Query firebaseSearchQuery = databaseCustomer.orderByChild("custName").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerOptions customerOptions = new FirebaseRecyclerOptions.Builder<Customer>()
.setQuery(firebaseSearchQuery, Customer.class).build();
adapter = new FirebaseRecyclerAdapter<Customer, CustomerList.ViewHolder>(customerOptions) {
#Override
protected void onBindViewHolder(#NonNull CustomerList.ViewHolder holder, int position, #NonNull Customer model) {
holder.setname(model.getCustName());
holder.setaddress(model.getCustAddress());
Toast.makeText(CRUDCustomer.this, model.custName,Toast.LENGTH_SHORT).show();
}
#NonNull
#Override
public CustomerList.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
};
listViewCustomer.setAdapter(adapter);
listViewCustomer.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
}
ViewHolder
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Customer customer = customerList.get(position);
holder.textName.setText(customer.getCustName());
holder.textAddress.setText(customer.getCustAddress());
holder.textPhone.setText(customer.getCustPhone());
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textName ;
public TextView textAddress;
public TextView textPhone ;
public ViewHolder(#NonNull View view){
super(view);
this.textName = (TextView)view.findViewById(R.id.cust_name);
this.textAddress = (TextView)view.findViewById(R.id.cust_address);
this.textPhone = (TextView)view.findViewById(R.id.cust_phone);
}
public void setname(String name){
textName.setText(name);
}
public void setaddress(String address){
textAddress.setText(address);
}
}
private void search(String text) {
List filterdNames = new ArrayList<>();
for (Modelclass s : modelclass) {
if (s.getname.contains(text)) {
search.add(s);
}
}
//calling a method of the adapter class and passing the filtered list
sampleAdapter.filterList(filterdNames);
}
I'm creating an Android app, the data that i'm sending through intent is being retrieved every time i click on the item.
I'm sending the retrieved data(which it's a subcollection that is being retrieved every time i click on item) through the intent,and all data receives in an arraylist, so the listener don't know if the same data existed in the arraylist,because the data are in the other activity.
when i click for the first time the data displayed normally in ItemMarkerActivity but when i go back and click again on the same item i see the data load again in the recycler view,and added to the previous same data, i'm using the technique of removing the data onStop but it didn't work perfectly,because i need to close all activities to see that the data removed, i tried to send the CollectionReference through intent but i couldn't do. so I need a way of removing the data immediately after closing the activity, and if anyone has another approach for solving this problem it would better.
Thanks in advance
adapter.setOnItemClickListener(new MarketAdapterRecyclerView.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
CollectionReference path = documentSnapshot.getReference().collection("ShoppingItems");
listener = path.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
if (dc.getType() == DocumentChange.Type.ADDED) {
item = dc.getDocument().toObject(Item.class);
itemList.add(item);
}
}
Intent intent = new Intent (shoppingActivity.this, ItemMarkerActivity.class);
Log.v(TAG,"###################################" + itemList.toString());
intent.putExtra("keyName", itemList);
startActivity(intent);
}
});
}
}
The Activity That Receives The data
The Manifest
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> implements Parcelable{
public ArrayList<Item> ItemList;
public Context mContext;
private onMallListener mOnMallListener;
private static final int NO_POSITION = -1;
public ItemAdapter(ArrayList<Item> ItemList, Context mContext, onMallListener mOnMallListener) {
this.ItemList = ItemList;
this.mContext = mContext;
this.mOnMallListener = mOnMallListener;
}
protected ItemAdapter(Parcel in) {
ItemList = in.createTypedArrayList(Item.CREATOR);
}
public static final Creator<ItemAdapter> CREATOR = new Creator<ItemAdapter>() {
#Override
public ItemAdapter createFromParcel(Parcel in) {
return new ItemAdapter(in);
}
#Override
public ItemAdapter[] newArray(int size) {
return new ItemAdapter[size];
}
};
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_card_view_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view, mOnMallListener);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Item item = ItemList.get(i);
viewHolder.itemType.setText(ItemList.get(i).getItemType());
Picasso.with(mContext)
.load(item.getImageUrl())
.fit()
.centerCrop().into(viewHolder.imageUrl);
}
#Override
public int getItemCount() {
return ItemList.size();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(ItemList);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
public TextView price;
public TextView description;
public TextView itemType;
public ImageView imageUrl;
onMallListener onMallListener;
public ViewHolder(#NonNull View itemView, onMallListener mOnMallListener) {
super(itemView);
mView = itemView;
itemType = (TextView) mView.findViewById(R.id.card_view_image_title);
imageUrl = (ImageView) mView.findViewById(R.id.card_view_image);
this.onMallListener = mOnMallListener;
mView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(mOnMallListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mOnMallListener.onMallClick(position);
}
}
}
}
public interface onMallListener{
void onMallClick(int position);
}
}
Save data using Room database in first activity and retrieve it in second.
In any place of your code (and in any activity's callback) you can clean db and all lists/recyclers which listen this data.
https://developer.android.com/training/data-storage/room
Hope it'll help
I'm trying to delete an item from my RecyclerView when the user clicks on it. However, even though the delete method in the Adapter is public I get the error 'Cannot resolve method delete(int)' when trying to call 'delete' method from the onClick in MyViewHolder.
What gives? It's public so why can't I call it?
GroceryItemAdapter
public class GroceryItemAdapter extends RecyclerView.Adapter<MyViewHolder> {
private LayoutInflater inflater;
private Context context;
List<MetaData> data = Collections.emptyList();
public GroceryItemAdapter(Context context, List<MetaData> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.grocery_item_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
Log.i("GroceryHero", "onCreateViewHolder called");
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MetaData current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconid);
Log.i("GroceryHero","onBindViewHolder called " + position);
}
#Override
public int getItemCount() {
return data.size();
}
}
MyViewHolder:
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
Log.i("GroceryHero", "MyViewHolder called");
title = (TextView) itemView.findViewById(R.id.grocery_text);
icon = (ImageView) itemView.findViewById(R.id.grocery_icon);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Item clicked at " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
delete(getAdapterPosition()); // ERROR: Cannot resolve method
}
}
You're trying to call delete from the view holder class. But delete is a method of the adapter class. You can may be pass an instance of adapter to the view holder in onCreateViewHolder and store it as a private field.
GroceryItemAdapter mAdapter;
public MyViewHolder(View itemView, GroceryItemAdapter adapter) {
mAdapter = adapter;
...
}
// now you can call
mAdapter.delete(getAdapterPosition());