get int data from firestore - java

im trying to get int data from firestore but before that app crashes i dont know why when i try it as string it work i get it and i can list it but when i try it int app crashes even before get data
here is my code second part is my adapter logchat said 2 line is wrong i mark it with stairs for u
FirebaseFirestore firestore;
ArrayList<String> useremaillist;
ArrayList<Integer> userpointlist;
SkorAdapter skorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skor_board);
firestore=FirebaseFirestore.getInstance();
useremaillist=new ArrayList<>();
userpointlist=new ArrayList<>();
getscore();
RecyclerView skorboardrecyclerView=findViewById(R.id.recyclerView);
skorboardrecyclerView.setLayoutManager(new LinearLayoutManager(this));
skorAdapter=new SkorAdapter(useremaillist,userpointlist);
skorboardrecyclerView.setAdapter(skorAdapter);
}
public void getscore(){
CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
collectionReference.orderBy("skor", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
userpointlist.clear();
useremaillist.clear();
if(error!=null){
Log.e("tag",error.getLocalizedMessage());
}
if(value!=null){
for(DocumentSnapshot snapshot:value.getDocuments()){
Map<String,Object> userdatat=snapshot.getData();
String emailt=(String) userdatat.get("email");
int skor=(int) userdatat.get("skor");
useremaillist.add(emailt);
userpointlist.add(skor);
skorAdapter.notifyDataSetChanged();
}
}
}
});
}
** public class SkorAdapter extends RecyclerView.Adapter<SkorAdapter.Holder> {
private ArrayList<String> emaillistforadapter;
private ArrayList<Integer> pointlistforadapter;
public SkorAdapter(ArrayList<String> emaillistforadapter,ArrayList<Integer> pointlistforadapter ) {
this.emaillistforadapter = emaillistforadapter;
this.pointlistforadapter = pointlistforadapter;
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.skorboard_row,parent,false);
return new Holder(view);
}
#Override
public void onBindViewHolder(#NonNull SkorAdapter.Holder holder, int position) {
holder.useremailtext.setText(emaillistforadapter.get(position));
** holder.userpointtext.setText(pointlistforadapter.get(position));
}
#Override
public int getItemCount() {
return emaillistforadapter.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView useremailtext;
TextView userpointtext;
public Holder(#NonNull View itemView) {
super(itemView);
useremailtext=itemView.findViewById(R.id.kullanıcımailtext);
userpointtext=itemView.findViewById(R.id.kullanıcıpointtext);
}
}

The problem is in the adapter then.
You have a private ArrayList<Integer> pointlistforadapter; and the problem is that you are doing holder.userpointtext.setText(pointlistforadapter.get(position)); and setText() accepts a CharSeq and it lets you add an Int in paramter because it also has this signature :
And since it's not a resid it crashes.
What you can do is :
holder.userpointtext.setText(pointlistforadapter.get(position).toString());

Related

Im getting error in startListening() stopListening()

This is the code in which I'm getting errors in startListening() and stopListening():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_app_cart,container,false);
recyclerView = view.findViewById(R.id.recylervieww);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
cartmodelList = new ArrayList<>();
cartadapt = new cartAdapter(getActivity(),cartmodelList);
recyclerView.setAdapter(cartadapt);
FirebaseRecyclerOptions<Cartmodel> options =
new FirebaseRecyclerOptions.Builder<Cartmodel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("Cart List"), Cartmodel.class)
.build();
cartadapt = new cartAdapter(options);
recyclerView.setAdapter(cartadapt);
return view;
}
#Override
public void onStart() {
super.onStart();
cartadapt.startListening();
}
#Override
public void onStop() {
super.onStop();
cartadapt.stopListening();
}
}
This is the code for cartAdapter:
public class cartAdapter extends RecyclerView.Adapter<cartAdapter.ViewHolder> {
Context context;
List<Cartmodel> cartmodelList;
public cartAdapter(Context context, List<Cartmodel> cartmodelList) {
this.context = context;
this.cartmodelList = cartmodelList;
}
public cartAdapter(FirebaseRecyclerOptions<Cartmodel> options) {
}
#NonNull
#Override
public cartAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_singlero,parent,false));
}
#Override
public void onBindViewHolder(#NonNull cartAdapter.ViewHolder holder, int position) {
holder.productName.setText(cartmodelList.get(position).getProductName());
holder.quantity.setText(cartmodelList.get(position).getQuantity());
holder.totalPrice.setText(cartmodelList.get(position).getTotalPrice());
Glide.with(holder.itemView.getContext()).load(Cartmodel.productImage()).into(holder.productImage);
}
#Override
public int getItemCount() {
return cartmodelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView date,productName,productPrice,quantity,totalPrice;
ImageView productImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
productName = itemView.findViewById(R.id.pnametext);
quantity = itemView.findViewById(R.id.quantity);
totalPrice = itemView.findViewById(R.id.totalprice);
productImage = itemView.findViewById(R.id.img2);
}
}
}
I'm getting these errors:
Cannot resolve method 'startListening' in 'cartAdapter'
Cannot resolve method 'stopListening' in 'cartAdapter'
I'm using both classes in another activity but in those, I'm not getting any errors.
I'm getting error in startListening() and stopListening()
Because those methods are not present inside RecyclerView.Adapter class. Your adapter class should extend FirebaseRecyclerAdapter class instead in order to be able to call startListening() and stopListening().
For more info, please check the official documentation:
https://firebaseopensource.com/projects/firebase/firebaseui-android/database/readme/

write to Firebaseon recycler adapter

I have a recycler view that is being populated by firebase database. On the item.xml I have a button alongside data. On clicking the button on each item, I want to save supplier name in my database. Get error: nullpointer exception as my class Suppliers remains null. What is causing it?
Code
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
Context context;
ArrayList<supplierClass> list;
public recyclerAdapter(Context context, ArrayList<supplierClass> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
supplierClass sc = list.get(position);
holder.sName.setText(sc.getsName());
holder.materialName.setText(sc.getMaterialName());
holder.CATEGORY.setText(sc.getCATEGORY());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView sName,materialName,CATEGORY;
Button btnSelect;
DatabaseReference ref;
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
public MyViewHolder(#NonNull View itemView) {
super(itemView);
sName = itemView.findViewById(R.id.lblSupplierName);
materialName = itemView.findViewById(R.id.lblMaterial);
CATEGORY = itemView.findViewById(R.id.lblLocation);
btnSelect=itemView.findViewById(R.id.btnSelect);
supplierClass sc=new supplierClass();
String id=user.getUid();
btnSelect.setOnClickListener(v -> {
ref= FirebaseDatabase.getInstance().getReference("dashboard");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
ref.child(id).setValue(sc.getsName());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
});
}
}

How to take value from dynamic edit text in Adapter

I have a RecyclerView with one edit text in Adapter where the editText is dynamic based on object present inside the array, How can i take the value of each edittext ?
public class AdapterFastagEditList extends RecyclerView.Adapter<AdapterFastagEditList.ViewHolder> {
Activity activity;
List<JSONObject> list;
OnItemViewClickListener onItemViewClickListener;
public AdapterFastagEditList(Activity activity, List<JSONObject> list, OnItemViewClickListener onItemViewClickListener) {
this.activity = activity;
this.list = list;
this.onItemViewClickListener = onItemViewClickListener;
}
public void setOnItemViewClickListener(OnItemViewClickListener onItemViewClickListener) {
this.onItemViewClickListener = onItemViewClickListener;
}
#NonNull
#Override
public AdapterFastagEditList.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// Initialize view for recyclerview
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
AdapterDynamicEdittextFastagBinding binding = AdapterDynamicEdittextFastagBinding.inflate(inflater, parent, false);
return new ViewHolder(binding.getRoot(), binding);
}
JSONObject object = new JSONObject();
#Override
public void onBindViewHolder(#NonNull AdapterFastagEditList.ViewHolder holder, int position) {
object = list.get(position);
AdapterDynamicEdittextFastagBinding binding = holder.binding;
try {
binding.TextInputContent.setHint(object.getString("BdetailsFieldName"));
binding.EditTextContent.setId(View.generateViewId());
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
AdapterDynamicEdittextFastagBinding binding;
public ViewHolder(#NonNull View itemView, AdapterDynamicEdittextFastagBinding binding) {
super(itemView);
this.binding = binding;
}
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
AdapterDynamicEdittextFastagBinding binding;
public ViewHolder(#NonNull View itemView, AdapterDynamicEdittextFastagBinding binding) {
super(itemView);
this.binding = binding;
binding.yourEdittext.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
//s.toString() gives you changes
//getAdapterPosition() also gives you changed item index
}
});
}
}

Method cannot resolve in Android

I have a problem where the method "deleteItem" cannot be resolved at this line adapters.deleteItem(viewHolder.getAdapterPosition());even I have created that method at public void deleteItem(int position).Do I placed the method wrongly?
Java codes:
final FirestoreRecyclerAdapter adapters;
fStore = FirebaseFirestore.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String current = user.getUid();
Query query = fStore.collection("Users").document(user.getUid()).collection("Diary");
FirestoreRecyclerOptions<ModelClass> options = new FirestoreRecyclerOptions.Builder<ModelClass>()
.setQuery(query, ModelClass.class)
.build();
adapters = new FirestoreRecyclerAdapter<ModelClass, ModelViewHolder>(options) {
#NonNull
#Override
public ModelViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_diary, parent, false);
return new ModelViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull ModelViewHolder holder, int position,
#NonNull ModelClass model) {
holder.date.setText(model.getDate());
holder.note.setText(model.getText());
holder.time.setText(model.getTime());
holder.divider.setText(model.getDivider());
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
};
adapters.startListening();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
SpacingItemDecoration itemDecorator = new SpacingItemDecoration(20);
recyclerView.addItemDecoration(itemDecorator);
recyclerView.setAdapter(adapters);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
adapters.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
public class ModelViewHolder extends RecyclerView.ViewHolder {
TextView date, time, note, divider;
public ModelViewHolder(#NonNull View itemView) {
super(itemView);
date = itemView.findViewById(R.id.date_text);
time = itemView.findViewById(R.id.time_textview);
note = itemView.findViewById(R.id.note_textview);
divider = itemView.findViewById(R.id.line_textview);
}
}
You can't do it since adapters is a FirestoreRecyclerAdapter which doesn't contain this method.
Just extend the FirestoreRecyclerAdapter and use it.
public class CustomAdapter extends FirestoreRecyclerAdapter<....>{
public CustomAdapter(#NonNull FirestoreRecyclerOptions<....> options) {
super(options);
}
public void deleteItem(int i){ ... }
#Override
protected void onBindViewHolder(){....}
#Override
public ModelViewHolder onCreateViewHolder(){ ...}
}

Shuffle items from Firebase Database

How to shuffle items from Firebase Database?
Let's say my DB contains 4 items [1,2,3,4]. In my RecyclerView, I want to display shuffled, something like [2,3,1,4]. How can I do that?
This is the code in my Fragment. So it works retrieving data but I need to shuffle it before displaying.
RecyclerView mRecyclerView;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mRef;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_store, viewGroup, false);
setHasOptionsMenu(false);
mRecyclerView = rootView.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
mFirebaseDatabase = FirebaseDatabase.getInstance();
mRef = mFirebaseDatabase.getReference("Store");
}
return rootView;
}
For retrieving data from Firebase Database I am using the following code:
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Store2> options =
new FirebaseRecyclerOptions.Builder<Store2>()
.setQuery(mRef, Store2.class)
.build();
FirebaseRecyclerAdapter<Store2, StoreHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Store2, StoreHolder>(options) {
#NonNull
#Override
public StoreHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.store_gridview, parent, false);
return new StoreHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final StoreHolder holder, int position, #NonNull final Store2 model) {
holder.setDetails(getContext(), model.getImage(), model.getName(), model.getPrice());
}
};
firebaseRecyclerAdapter.startListening();
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
There are no option available for shuffling data in firebase.
But you can do it locally .
Pass your list in this.
Collections.shuffle(arrayList);
When you are using the following reference:
mRef = mFirebaseDatabase.getReference("Store");
It means that you are trying to display all children that exist under Store node. If under this node you store children that are added using the push() method, the default ordering is chronological, since every pushed id contains a time component. If you want to change this behaviour, you need to get all the items and shuffle them manually.
As #DougStevenson mentioned in his comment, you have to use the same reference, get all items, add them to a list, shuffle them and then use a ListAdapter for that.
Please also note, that when you pass a DocumentReference or a Query object to the setQuery() method, where is no further mechanism that can help you shuffle your items. Unfortunately, you'll lose the benefits of the Firebase-UI library but you'll get your work done.
As #DougStevenson and #frankenstein mentioned, I added all items into a list, then I was able the shuffle it using Collections.shuffle(arrayList);
I couldn't do it using FirebaseRecyclerAdapter, and I needed a custom Adapter for my RecyclerView.ViewHolder.
What is the downside of not using FirebaseRecyclerAdapter? Or is it any? Maybe someone with experience can answer this question.
My fragment:
private View rootView;
private RecyclerView recyclerView;
private StoreAdapter storeAdapter;
private ArrayList<Store> arrayStore;
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_store, viewGroup, false);
setHasOptionsMenu(false);
recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Data");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayStore = new ArrayList<>();
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
Store store = snapshot.getValue(Store.class);
arrayStore.add(store);
}
storeAdapter = new StoreAdapter(getActivity() ,arrayStore);
recyclerView.setAdapter(storeAdapter);
Collections.shuffle(arrayStore, new Random(3));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
return rootView;
}
My adapter:
private final Context context;
private ArrayList<Store> arrayStore;
public StoreAdapter(Context context, ArrayList<Store> arrayStore) {
this.context = context;
this.arrayStore = arrayStore;
}
#NonNull
#Override
public StoreAdapter.GameViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new StoreAdapter.GameViewHolder(LayoutInflater.from(context).inflate(
R.layout.store_gridview, viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull final StoreAdapter.GameViewHolder viewHolder, final int position) {
setColor(viewHolder);
viewHolder.itemName.setText(arrayStore.get(position).getName());
Glide.with(viewHolder.view.getContext())
.load(arrayStore.get(position).getImage())
.thumbnail(0.75f)
.into(viewHolder.itemImage);
viewHolder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData(viewHolder, position);
}
});
}
#Override
public int getItemCount() {
return arrayStore.size();
}
class GameViewHolder extends RecyclerView.ViewHolder {
private final View view;
private final ImageView itemImage, itemRarity;
private final TextView itemName;
GameViewHolder(#NonNull View itemView) {
super(itemView);
this.view = itemView;
itemRarity = view.findViewById(R.id.itemRarity);
itemImage = view.findViewById(R.id.itemImage);
itemName = view.findViewById(R.id.itemName);
}
}
private void sendData(#NonNull final StoreAdapter.GameViewHolder viewHolder, int position) {
if (viewHolder.getAdapterPosition() != RecyclerView.NO_POSITION) {
Intent intent = new Intent(context, DetailsActivity.class);
intent.putExtra("name", arrayStore.get(position).getName());
intent.putExtra("rarity", arrayStore.get(position).getRarity());
intent.putExtra("item", arrayStore.get(position).getImage());
intent.putExtra("price", arrayStore.get(position).getPrice());
intent.putExtra("key", "Store");
context.startActivity(intent);
}
}
private void setColor(#NonNull final StoreAdapter.GameViewHolder viewHolder) {
String rarity = arrayStore.get(viewHolder.getAdapterPosition()).getRarity();
if (rarity.contains("legendary")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_legendary_gradient);
} else if (rarity.contains("classic")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_classic_gradient);
} else if (rarity.contains("epic")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_epic_gradient);
} else if (rarity.contains("elite")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_elite_gradient);
} else if (rarity.contains("rare")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_rare_gradient);
} else if (rarity.contains("special")) {
viewHolder.itemRarity.setImageResource(R.drawable.color_special_gradient);
}
}
My bean class:
private String image, name, price, rarity;
public Store() {
}
public String getImage() {
return image;
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getRarity() {
return rarity;
}

Categories

Resources