I have a problem with Recycler view. it does not appear when i close and reopen the application.
1) Im using fragments, when i add an item to the recycler it appears normally:
https://i.stack.imgur.com/4Y8X6.png
2) When I close the app and then reopen it, the image doesn't load.
onCreateView of my fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_home,container,false);
loadRecycler();
return v;
}
loadRecycler() method:
private void loadRecycler() {
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Users").child("Animales");
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
for(DataSnapshot snap: dataSnapshot.getChildren()){
Animal animal = snap.getValue(Animal.class);
mlist.add(new AnimalAdapterData(animal.getNombre(),animal.getImageURL()));
}
}
recyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
onViewCreated method:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
recyclerView = v.findViewById(R.id.recycler_view);
adapter = new HomeAdapter(getActivity(),mlist);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2,GridLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
}
HomeAdapter class:
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {
private Context context;
private List<AnimalAdapterData> mData;
public HomeAdapter(Context context, List<AnimalAdapterData> mData) {
this.context = context;
this.mData = mData;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.grid_item,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
AnimalAdapterData currentItem = mData.get(position);
String imageUrl = currentItem.getImageURL();
String title = currentItem.getNombre();
holder.mTextView.setText(title);
Picasso.get().load(imageUrl).fit().centerInside().into(holder.mImageView);
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView mImageView;
TextView mTextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView = itemView.findViewById(R.id.textView);
}
}
}
I think that im using correctly the onCreateView and onViewCreated method, but idk whats going on with this.
Related
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/
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) {
}
});
});
}
}
I am a beginner at android development. I tried to display data on Recycle View using MVVM. When I opened the fragment the first time it is empty, the second time it showed data. Adapter not called the first time. How to fix this.
Fragment class
public class fragmentEmployee extends Fragment {
private FragmentEmployeeBinding binding;
private ViewGroup viewGroup;
private View view;
private RecyclerView mRecycleView;
private UserAdapter mAdapter;
private EmployeeRegisterViewModel viewModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_employee, viewGroup, false);
view = binding.getRoot();
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toast.makeText(getContext(), "onViewCreated", Toast.LENGTH_SHORT).show();
mRecycleView = binding.recyleViewEmployee;
viewModel = new ViewModelProvider(this).get(EmployeeRegisterViewModel.class);
viewModel.init();
initRecycleView();
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
}
private void initRecycleView() {
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
mRecycleView.setLayoutManager(layoutManager);
mRecycleView.setAdapter(mAdapter);
}
}
UserAdapter class
public class UserAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public List<employeeModel> employeeModelList= new ArrayList<>();
public Context context1;
public UserAdapter(Context context,List<employeeModel> employeeModels){
employeeModelList = employeeModels;
context1 = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem,parent,false);
ViewHolder viewHolder=new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
(ViewHolder)holder).username.setText(employeeModelList.get(position).getName());
}
#Override
public int getItemCount() {
return employeeModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView username;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.userText);
}
}
}
Try reordering like this.
Remove
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
from initRecycleView
mAdapter = new UserAdapter(getContext(), viewModel.getEmployee().getValue());
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
initRecycleView();
mAdapter.notifyDataSetChanged();
Above method will work if the list declared inside adapter has any change. So, calling above method without changing adapter's list is useless.
Add a method to UserAdapter class to update list data. Like:
public void updateData(List<employeeModel> updatedList){
employeeModelList.clear();
employeeModelList.addAll(updatedList);
notifyDataSetChanged();
}
And call this method inside observer. Like:
viewModel.getEmployee().observe(getViewLifecycleOwner(), new
Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.updateData(employeeModels);
}
});
where are you get your network data?
If your get in here -> viewModel.init();
I think it just timing problem.
Just change code sequence
initRecycleView();
viewModel.getEmployee().observe(getViewLifecycleOwner(), new Observer<List<employeeModel>>() {
#Override
public void onChanged(List<employeeModel> employeeModels) {
mAdapter.notifyDataSetChanged();
}
});
viewModel.init();
I'm trying to add a recyclerview to a fragment, but somehow there happens to be an error in the adapter.
I think it is the way in which I bind it, and I can't figure out the solution to it. Can anybody help me solve the issue?
here's my adapter:
public class MyLeaguesListAdapter extends
RecyclerView.Adapter<MyLeaguesListAdapter.MyViewHolder>{
List<MyContest> listItems;
Context context;
public interface OnItemClickListener {
void onItemClick(View v,int pos);
}
public MyLeaguesListAdapter(List<MyContest> listItems,Context context){
this.listItems = listItems;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate(R.layout.my_contest_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(v);
return myViewHolder;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView leagueName,playerName,prizePool,playerRank,playerPoints,entryFee,spots;
OnItemClickListener onItemCheckListener;
public MyViewHolder(View itemView) {
super(itemView);
leagueName = (TextView) itemView.findViewById(R.id.mc_contest_name);
playerName = (TextView) itemView.findViewById(R.id.mc_player_name);
prizePool = (TextView) itemView.findViewById(R.id.mc_prize_pool);
playerRank = (TextView) itemView.findViewById(R.id.mc_player_rank);
playerPoints = (TextView) itemView.findViewById(R.id.mc_player_points);
entryFee = (TextView) itemView.findViewById(R.id.mc_entry_fee);
spots = (TextView) itemView.findViewById(R.id.mc_spots);
itemView.setOnClickListener(this);
}
public void setItemClickListener(OnItemClickListener ic){
this.onItemCheckListener = ic;
}
#Override
public void onClick(View view) {
this.onItemCheckListener.onItemClick(view,getAdapterPosition());
}
}
#Override
public int getItemCount() {
return listItems.size();
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
MyContest listItem = listItems.get(position);
holder.leagueName.setText(listItem.getLeaguename());
holder.prizePool.setText(listItem.getPrizepool());
holder.playerPoints.setText(listItem.getScore());
holder.playerRank.setText(listItem.getRank());
holder.playerName.setText(listItem.getUsername());
holder.spots.setText(listItem.getSpots());
holder.entryFee.setText(listItem.getFee());
holder.setItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
}
});
}
}
this is my fragment:
public class MyLeagues extends Fragment {
SharedPreferences sharedPreferences,ui;
int score,userid,i=0;
String username,lname,inviteCode;
List<MyContest> list_item;
MyLeaguesListAdapter adapter;
ProgressBar progressBar;
Sprite fadingCircle;
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_leagues,null);
ui = this.getActivity().getSharedPreferences("User",Context.MODE_PRIVATE);
userid = ui.getInt("userid",-1);
progressBar = (ProgressBar) view.findViewById(R.id.mcspin_kit);
fadingCircle = new FadingCircle();
progressBar.setIndeterminateDrawable(fadingCircle);
Log.d("eede", "onCreateView: "+inviteCode);
recyclerView = (RecyclerView) view.findViewById(R.id.mc_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
list_item = new ArrayList<>();
getMYContests();
return view;
}
public void getMYContests(){
Call<MyContestResponse> call = RetrofitClient
.getInstance()
.getApi()
.getMycontests(userid);
call.enqueue(new Callback<MyContestResponse>() {
#Override
public void onResponse(Call<MyContestResponse> call, Response<MyContestResponse> response) {
list_item=response.body().getData();
adapter = new MyLeaguesListAdapter(list_item,getContext());
progressBar.setVisibility(View.INVISIBLE);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<MyContestResponse> call, Throwable t) {
Log.d("bruv", "onFailure: "+t);
}
});
}
}
error:
07-03 09:36:20.980 30095-30095/? E/AndroidRuntime: FATAL EXCEPTION:
main
Process: com.example.android.khelo, PID: 30095
android.content.res.Resources$NotFoundException: String resource ID #0xffffffff
at android.content.res.Resources.getText(Resources.java:363)
at android.widget.TextView.setText(TextView.java:6485)
at com.example.android.khelo.MyLeaguesListAdapter.onBindViewHolder(MyLeaguesListAdapter.java:75)
at com.example.android.khelo.MyLeaguesListAdapter.onBindViewHolder(MyLeaguesListAdapter.java:20)
from what I've read, the issue is with the way I bind the recylerview but I've not got a clear idea about where the issue actually lies.
It is possible that one or many of your listItem attributes return an integer like getScore and getFee. So let's look at the implementation of TextView.setText(int)
public final void setText(int resid) {
...
}
As you can see, it only accepts the int as a resource id like R.string.something.
So what you can do here is to make your int become string when setText like
holder.playerPoints.setText(listItem.getScore().toString());
I have a recyclerView. Values are lost when recycler is scrolled down.I would like to have values greater than 7. Values come up when first opened but When I go down the scroll bar, it returns to its original state.
FragmentB.java
public class FragmentB extends Fragment{
View view ;
TextView textView;
RecyclerView recyclerView ;
ArrayList<OnemliDepremler> onemliDepremler;
BuyukRecyclerAdapter buyukRecyclerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_sabit,container,false);
// textView=view.findViewById(R.id.textView3);
recyclerView = view.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.scrollToPosition(0);
recyclerView.setLayoutManager(layoutManager);
onemliDepremler=new ArrayList<OnemliDepremler>();
Factory.getInstance().buyukDepremModel().enqueue(new Callback<OnemliDepremModel>() {
#Override
public void onResponse(Call<OnemliDepremModel> call, Response<OnemliDepremModel> response) {
buyukRecyclerAdapter=new BuyukRecyclerAdapter(response.body().data.subList(0, 10));
recyclerView.setAdapter(buyukRecyclerAdapter);
}
#Override
public void onFailure(Call<OnemliDepremModel> call, Throwable t) {
}
});
return view;
}
}
BuyukRecyclerAdapter.java
public class BuyukRecyclerAdapter extends RecyclerView.Adapter<BuyukRecyclerAdapter.ViewHolder> {
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView buyukluk;
public TextView yer;
public TextView tarih;
public CardView cardView ;
FrameLayout frameLayout;
public ViewHolder(View itemView) {
super(itemView);
cardView = itemView.findViewById(R.id.card_view);
buyukluk=itemView.findViewById(R.id.text_buyukluk);
yer=itemView.findViewById(R.id.text_yer);
tarih=itemView.findViewById(R.id.text_tarih);
frameLayout=itemView.findViewById(R.id.frame_layout);
}
}
List<Datum> onemliDepremler;
public BuyukRecyclerAdapter(List<Datum> onemliDepremler) {
this.onemliDepremler = onemliDepremler;
}
#Override
public BuyukRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.onemli_custom,parent,false);
final ViewHolder view_holder=new ViewHolder(v);
return view_holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.buyukluk.setText(onemliDepremler.get(position).siddeti);
holder.tarih.setText("Tarih :"+onemliDepremler.get(position).tarih);
holder.yer.setText(onemliDepremler.get(position).lokasyon);
if(Float.parseFloat(onemliDepremler.get(position).siddeti)>7){
holder.frameLayout.setBackgroundColor(Color.RED);
}
}
#Override
public int getItemCount() {
return onemliDepremler.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Your advice important for me
Thank you very much !
if(Float.parseFloat(onemliDepremler.get(position).siddeti)>7){
holder.frameLayout.setBackgroundColor(Color.RED);
}else{
holder.frameLayout.setBackgroundColor(Color.YELLOW);
}
Try this.