recyclerview list not showing data passed through arraylist - java

My code was worked perfectly just before i added header image, after that listview not showing the given datas.
These are the main pages.
Can anyone help please.Any help will be appreciated.
MyRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyRecyclerViewAdapter extends
RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
Context context;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public MyRecyclerViewAdapter(String[] data) {
this.data = data;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView desc;
ImageView image,head_img;
public DataObjectHolder(View itemView) {
super(itemView);
desc = (TextView) itemView.findViewById(R.id.description);
image = (ImageView) itemView.findViewById(R.id.image);
head_img=(ImageView) itemView.findViewById(R.id.header_img);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
this.mDataset = myDataset;
this.context=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType==TYPE_ITEM) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
else if (viewType==TYPE_HEADER){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
//DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return new DataObjectHolder(view);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
if(holder instanceof VHItem) {
holder.desc.setText(mDataset.get(position ).getDescription());
// holder.image.setText(mDataset.get(position).getImage_url());
Picasso.with(holder.image.getContext()).load(mDataset.get(position ).getImage_url()).into(holder.image);
}
else if(holder instanceof VHHeader){
holder.head_img.setImageResource(R.drawable.cam);
}
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return (null != mDataset ? mDataset.size() + 1 : 0);
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
private class VHItem extends DataObjectHolder {
public VHItem(View itemView) {
super(itemView);
}
}
private class VHHeader extends DataObjectHolder {
public VHHeader(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
}
Profile2Fragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Profile2Fragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.recycler_view, container, false);
mRecyclerView = (RecyclerView) rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
return rootview;
}
private ArrayList<DataObject> getDataSet() {
ArrayList<DataObject> results = new ArrayList<DataObject>();
for (int index = 0; index < 1; index++) {
DataObject obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://mediastream.jumeirah.com/webimage/heroactual//globalassets/global/hotels-and-resorts/dubai/madinat-jumeirah/restaurants/pierchic/madinat-jumeirah-pierchic-inside-restaurant-02-hero.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "https://photos.smugmug.com/Portfolio/i-HBk894k/0/db7f0344/L/The%20Black%20Couches-L.jpg");
results.add(obj);
obj = new DataObject("Lorem Ipsum is simply\n dummy text of the", "http://thesmartlocal.com/images/easyblog_images/82/Pollen.jpg");
results.add(obj);
}
return results;
}
}
DataObject.java
public class DataObject {
private String description;
private String image_url;
DataObject (String text1, String text2){
description = text1;
image_url = text2;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

try to change return statement
`return new DataObjectHolder(view);
to your specific Class like return
new VHHeader(view);
and
return new VHItem(view);
in onCreateViewHolder..

Related

How to Pass data with onclickListener to other fragment in RecyclerView

I am retrieving Cloud Firestore data in Modelo.class and I'm trying to pass these variables from the to fragment DescDenuncia using a adapter Adapter.class but to do that I need to get the context tfor it using the I've already tried use AppCompatActivity activity = (AppCompatActivity) view.getContext();, but my app crashes every time I run this line, and is necessary to use a Context in the getSupportFragmentManager() to it works. If i'm doing this in a wrong way please tell me I truly don't know what I should do, please someone answer me
I'm using this video https://www.youtube.com/watch?v=QgfNl541oso&t=2449s
Modelo.java
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Home.java
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class Home extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RecyclerView recview;
Adapter adapter;
public static Home newInstance(String param1, String param2) {
Home fragment = new Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recview = view.findViewById(R.id.rvDenuncias);
recview.setLayoutManager(new LinearLayoutManager(getContext()));
Query query = FirebaseFirestore.getInstance()
.collection("Ocorrencias")
.limit(50);
FirestoreRecyclerOptions<Modelo> options = new FirestoreRecyclerOptions.Builder<Modelo>()
.setQuery(query, Modelo.class)
.build();
adapter = new Adapter(options);
recview.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter.java
package com.example.safe;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
//Ação de entrar abrir a ocorrência
holder.RLAYOUT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///////////////////////////////////////THE PROBLEM IS HERE///////////////////////////////////////////
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
//importando as variáveis do Modelo e enviado para o DescDenun
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
DescDenuncia.java
package com.example.safe;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.firebase.firestore.FirebaseFirestore;
public class DescDenuncia extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
ImageButton bt_Voltar, bt_Manutencao;
FirebaseFirestore db = FirebaseFirestore.getInstance();
public DescDenuncia() {
}
public DescDenuncia(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public static DescDenuncia newInstance(String param1, String param2) {
DescDenuncia fragment = new DescDenuncia();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_desc_denuncia, container, false);
TextView EmprHolder = view.findViewById(R.id.txtDenunEmpr);
TextView AreaHolder = view.findViewById(R.id.txtDenunArea);
TextView SetorHolder = view.findViewById(R.id.txtDenunSetor);
TextView TipoHolder = view.findViewById(R.id.txtDenunTipo);
TextView RiscoHolder = view.findViewById(R.id.txtDenunRisco);
ImageView ImgDenun = view.findViewById(R.id.txtDenunImg);
TextView DataHolder = view.findViewById(R.id.txtDenunData);
TextView PrazoHolder = view.findViewById(R.id.txtDenunPrazo);
TextView DescHolder = view.findViewById(R.id.txtDesc);
TextView ResolHolder = view.findViewById(R.id.txtFeedback);
//Definindo os as variáveis para o valor
EmprHolder.setText(empresa);
AreaHolder.setText(area);
SetorHolder.setText(setor);
TipoHolder.setText(tipo);
RiscoHolder.setText(risco);
Glide.with(getContext()).load(img).into(ImgDenun);
DataHolder.setText(data);
PrazoHolder.setText(prazo);
DescHolder.setText(desc);
ResolHolder.setText(resolucao);
return view;
}
public void onBackPressed()
{
AppCompatActivity activity=(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,new Home()).addToBackStack(null).commit();
}
}

How to pass the Rreclycler View iten variables to another fragment

I am retrieving Cloud Firestore data in Modelo.class and I'm trying to pass these variables from the to fragment DescDenuncia using a adapter Adapter.class but to do that I need to get the context tfor it using the I've already tried use AppCompatActivity activity = (AppCompatActivity) view.getContext();, but my app crashes every time I run this line, I think its necessary to use a Context in the getSupportFragmentManager() to it works. If i'm doing this in a wrong way please tell me I truly don't know what I should do, please someone answer me. I belive the problem in the action bar that I'm using in the TelaPrincial.class becuse the code works when there is no BottomNavigationView, or when I load the layout use it to load teh layout separately.
I'm using this video https://www.youtube.com/watch?v=QgfNl541oso&t=2449s
Home.java
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class Home extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
RecyclerView recview;
Adapter adapter;
public static Home newInstance(String param1, String param2) {
Home fragment = new Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Home() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recview = view.findViewById(R.id.rvDenuncias);
recview.setLayoutManager(new LinearLayoutManager(getContext()));
Query query = FirebaseFirestore.getInstance()
.collection("Ocorrencias")
.limit(50);
FirestoreRecyclerOptions<Modelo> options = new FirestoreRecyclerOptions.Builder<Modelo>()
.setQuery(query, Modelo.class)
.build();
adapter = new Adapter(options);
recview.setAdapter(adapter);
return view;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
Modelo
package com.example.safe;
public class Modelo {
String empresa, area, setor, tipo, risco, img, data, prazo, desc, resolucao, ID;
public Modelo() {
}
public Modelo(String empresa, String area, String setor, String tipo, String risco, String img, String data, String prazo, String desc, String resolucao, String ID) {
this.empresa = empresa;
this.area = area;
this.setor = setor;
this.tipo = tipo;
this.risco = risco;
this.img = img;
this.data = data;
this.prazo = prazo;
this.desc = desc;
this.resolucao = resolucao;
this.ID = ID;
}
public String getEmpresa() {
return empresa;
}
public void setEmpresa(String empresa) {
this.empresa = empresa;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getSetor() {
return setor;
}
public void setSetor(String setor) {
this.setor = setor;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getRisco() {
return risco;
}
public void setRisco(String risco) {
this.risco = risco;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getPrazo() {
return prazo;
}
public void setPrazo(String prazo) {
this.prazo = prazo;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getResolucao() {
return resolucao;
}
public void setResolucao(String resolucao) {
this.resolucao = resolucao;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
Adapter.class
package com.example.safe;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {
public Adapter(#NonNull FirestoreRecyclerOptions<Modelo> options) {
super(options);
}
//Sobrescrevendo o método
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull Modelo model) {
//Associando os itens do atalho ocorrências
holder.IDText.setText(model.getID());
holder.tipoText.setText(model.getTipo());
Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);
//Ação de entrar abrir a ocorrência
holder.RLAYOUT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppCompatActivity activity = (AppCompatActivity) view.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
//importando as variáveis do Modelo e enviado para o DescDenun
model.getEmpresa(),
model.getArea(),
model.getSetor(),
model.getTipo(),
model.getRisco(),
model.getImg(),
model.getData(),
model.getPrazo(),
model.getDesc(),
model.getResolucao(),
model.getID()
)).addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.modelo_atalho_ocorrencias, parent, false);
return new myviewholder(view);
}
//Coneção do reclycler view com essa classe
public class myviewholder extends RecyclerView.ViewHolder {
//Variáveis do modelo atalho
TextView tipoText, IDText;
RelativeLayout RLAYOUT;
ImageView img1;
//Associando os objetos ao modelo atalho
public myviewholder(#NonNull View itemView) {
super(itemView);
tipoText = itemView.findViewById(R.id.txtTipo);
img1 = itemView.findViewById(R.id.imageView);
IDText = itemView.findViewById(R.id.txtModeloID);
RLAYOUT = itemView.findViewById(R.id.RLlayout);
}
}
}
TelaPrincial.class
package com.example.safe;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
import com.example.safe.databinding.ActivityTelaPrincipalBinding;
public class TelaPrincipal extends AppCompatActivity {
private ActivityTelaPrincipalBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityTelaPrincipalBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch (item.getItemId()){
case R.id.Home:
reaplaceFragment(new Home());
break;
case R.id.Estatísticas:
reaplaceFragment(new Graph());
break;
case R.id.Denúncia:
reaplaceFragment(new Denuncia());
break;
case R.id.Perfil:
reaplaceFragment(new Perfil());
break;
case R.id.Config:
reaplaceFragment(new Config());
break;
}
return true;
});
}
private void reaplaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();
}
}

Sort Recyclerview item data By Category name from Firestore Android [duplicate]

This question already has an answer here:
Firebase Android ListView not being displayed
(1 answer)
Closed 1 year ago.
I am creating an Android Grocery Shop App, where firestore used. I am implementing a Nested Recyclerview where I have done coding for showing data from firestore to recycler view by Category Names.
But, all products are showing in the recyclerview, like the below image. Data is not sorted by category names.
Codes
ProductsAdapterbyCategory.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chattthedev.shoppingguskara.Activities.Models.ProductsModel;
import com.chattthedev.shoppingguskara.R;
import java.util.List;
public class ProductsAdapterbyCategory extends
RecyclerView.Adapter<ProductsAdapterbyCategory.ViewHolderForProducts> {
List<ProductsModel> productsbycat;
Context context;
public ProductsAdapterbyCategory(List<ProductsModel> productsbycat, Context context) {
this.productsbycat = productsbycat;
this.context = context;
}
#NonNull
#Override
public ViewHolderForProducts onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.singleforitembycat, parent, false);
ViewHolderForProducts viewHolderForProducts = new ViewHolderForProducts(view);
return viewHolderForProducts;
}
#Override
public void onBindViewHolder(#NonNull ViewHolderForProducts holder, int position) {
holder.catnameinprod.setText(productsbycat.get(position).getItemCategory());
ProductsAdapter2 productsAdapter2 = new ProductsAdapter2(productsbycat, context);
holder.recyclerViewinprod.setHasFixedSize(true);
holder.recyclerViewinprod.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
holder.recyclerViewinprod.setAdapter(productsAdapter2);
holder.recyclerViewinprod.setNestedScrollingEnabled(false);
}
#Override
public int getItemCount() {
return (productsbycat != null ? productsbycat.size() : 0);
}
public class ViewHolderForProducts extends RecyclerView.ViewHolder {
public TextView catnameinprod;
public Button viewmoreinprod;
public RecyclerView recyclerViewinprod;
public ViewHolderForProducts(#NonNull View itemView) {
super(itemView);
catnameinprod = itemView.findViewById(R.id.catnameforfetch);
viewmoreinprod = itemView.findViewById(R.id.buttviewmoreitem);
recyclerViewinprod = itemView.findViewById(R.id.recyclerprodfetch);
}
}
}
ProductsAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.chattthedev.shoppingguskara.Activities.Models.ProductsModel;
import com.chattthedev.shoppingguskara.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ProductsAdapter2 extends RecyclerView.Adapter {
List<ProductsModel> productsModelList;
Context context;
public ProductsAdapter2(List<ProductsModel> productsModelList, Context context) {
this.productsModelList = productsModelList;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_scroll_item, parent, false);
ProductsAdapter2.ViewHolderClass2 viewHolderClass = new ProductsAdapter2.ViewHolderClass2(view);
return viewHolderClass;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ProductsAdapter2.ViewHolderClass2 viewHolderClass = (ProductsAdapter2.ViewHolderClass2) holder;
ProductsModel productsModel = productsModelList.get(position);
viewHolderClass.proditemname.setText(productsModel.getItemname());
viewHolderClass.proditemprice.setText("Rs." + productsModel.getItemActualPrice() + "/-");
Picasso.get().load(productsModel.getItemImageUrl()).into(viewHolderClass.prodimage);
}
public void updatelist(List<ProductsModel> models){
productsModelList = new ArrayList<>();
productsModelList.addAll(models);
notifyDataSetChanged();
}
public Filter getFilter(){
return new Filter() {
private List<ProductsModel> filtered = new ArrayList<ProductsModel>();
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
filtered.clear();
if(charString.isEmpty()){
filtered = productsModelList;
//filteredCUG = CUG;
}
else{
for (ProductsModel cug : productsModelList){
if( cug.getItemname().toLowerCase().contains(charString)){
filtered.add(cug);
}
}
//filteredCUG = filtered;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filtered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
productsModelList = (List<ProductsModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
#Override
public int getItemCount() {
return productsModelList.size();
}
public class ViewHolderClass2 extends RecyclerView.ViewHolder {
TextView proditemname, proditemprice, productitemdiscount;
ImageView prodimage;
public ViewHolderClass2(#NonNull View itemView) {
super(itemView);
proditemname = itemView.findViewById(R.id.hsproducttitle);
proditemprice = itemView.findViewById(R.id.hsproductprice);
prodimage = itemView.findViewById(R.id.hsproductimage);
productitemdiscount = itemView.findViewById(R.id.hsproductdesc);
}
}
}
HomeFragment.java only providing the recyclerview fetching data function from firestore
private void getproductsfromcats() {
Query query = collectionReference.orderBy("ItemCategory");
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot queryDocumentSnapshot : queryDocumentSnapshots) {
ProductsModel productsModel = queryDocumentSnapshot.toObject(ProductsModel.class);
productsModelList2.add(productsModel);
}
productsAdapterbyCategory = new
ProductsAdapterbyCategory(productsModelList2,view.getContext());
product_items_for_cat.setAdapter(productsAdapterbyCategory);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(view.getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
});
}
ProductsModel.java
public class ProductsModel {
private String ItemActualPrice, ItemCategory, ItemDescription, ItemDiscount,
ItemFinalPrice, ItemId, ItemImageUrl, ItemStock, ItemUnit, ItemWeight,
Itemname;
public ProductsModel() {
}
public ProductsModel(String itemActualPrice, String itemCategory, String
itemDescription, String itemDiscount, String itemFinalPrice, String itemId,
String itemImageUrl, String itemStock, String itemUnit, String itemWeight,
String itemname) {
ItemActualPrice = itemActualPrice;
ItemCategory = itemCategory;
ItemDescription = itemDescription;
ItemDiscount = itemDiscount;
ItemFinalPrice = itemFinalPrice;
ItemId = itemId;
ItemImageUrl = itemImageUrl;
ItemStock = itemStock;
ItemUnit = itemUnit;
ItemWeight = itemWeight;
Itemname = itemname;
}
public String getItemActualPrice() {
return ItemActualPrice;
}
public void setItemActualPrice(String itemActualPrice) {
ItemActualPrice = itemActualPrice;
}
public String getItemCategory() {
return ItemCategory;
}
public void setItemCategory(String itemCategory) {
ItemCategory = itemCategory;
}
public String getItemDescription() {
return ItemDescription;
}
public void setItemDescription(String itemDescription) {
ItemDescription = itemDescription;
}
public String getItemDiscount() {
return ItemDiscount;
}
public void setItemDiscount(String itemDiscount) {
ItemDiscount = itemDiscount;
}
public String getItemFinalPrice() {
return ItemFinalPrice;
}
public void setItemFinalPrice(String itemFinalPrice) {
ItemFinalPrice = itemFinalPrice;
}
public String getItemId() {
return ItemId;
}
public void setItemId(String itemId) {
ItemId = itemId;
}
public String getItemImageUrl() {
return ItemImageUrl;
}
public void setItemImageUrl(String itemImageUrl) {
ItemImageUrl = itemImageUrl;
}
public String getItemStock() {
return ItemStock;
}
public void setItemStock(String itemStock) {
ItemStock = itemStock;
}
public String getItemUnit() {
return ItemUnit;
}
public void setItemUnit(String itemUnit) {
ItemUnit = itemUnit;
}
public String getItemWeight() {
return ItemWeight;
}
public void setItemWeight(String itemWeight) {
ItemWeight = itemWeight;
}
public String getItemname() {
return Itemname;
}
public void setItemname(String itemname) {
Itemname = itemname;
}
}
Firestore DB Structure Screenshot
you can create two different collection(meat,fruit) in firestore

Button inside RecyclerView

I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});

setonclicklistener effect every 4th position in recycler view

/**
* Created by Prateek on 2/18/2017.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import newsee.novasyslabs.com.nodefetch.Others.CircularTransform;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
Context mContext;
public static ArrayList <String> embed_html = new ArrayList<>();
public static ArrayList <String> channel_thumbnail = new ArrayList<>();
public static ArrayList <String> channel_title = new ArrayList<>();
public static ArrayList <String> video_title = new ArrayList<>();
public static ArrayList <String> created_time = new ArrayList<>();
public static ArrayList <Integer> android_likes = new ArrayList<>();
public static ArrayList <Integer> pf_likes = new ArrayList<>();
public static ArrayList <Integer> android_views = new ArrayList<>();
public static ArrayList <Integer> pf_views = new ArrayList<>();
public RecyclerAdapter(Context mContext){
this.mContext = mContext;
}
class ViewHolder extends RecyclerView.ViewHolder{
WebView webView;
public ImageView chlogo;
public TextView chtitle;
public TextView vidtitle;
public TextView upld_time;
public TextView show_views;
public TextView show_likes;
public ImageView mLike;
int j = 0;
public ViewHolder(View itemView) {
super(itemView);
this.mLike = (ImageView)itemView.findViewById(R.id.video_like);
this.show_views = (TextView) itemView.findViewById(R.id.video_views_count);
this.show_likes = (TextView) itemView.findViewById(R.id.likes_count);
this.webView = (WebView) itemView.findViewById(R.id.web);
this.chlogo = (ImageView) itemView.findViewById(R.id.ch_logo);
this.chtitle = (TextView) itemView.findViewById(R.id.ch_name);
this.vidtitle = (TextView) itemView.findViewById(R.id.video_title);
this.upld_time = (TextView)itemView.findViewById(R.id.ch_time);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.layout_card, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.j==0) {
holder.mLike.setImageResource(R.drawable.liked);
CharSequence like = holder.show_likes.getText();
int new_like = Integer.parseInt((String) like) + 1;
Toast.makeText(mContext,"Liked" +new_like ,Toast.LENGTH_SHORT).show();
holder.j = 1;
} else {
holder.mLike.setImageResource(R.drawable.unlike);
CharSequence like = holder.show_likes.getText();
int new_like = Integer.parseInt((String) like) - 1;
Toast.makeText(mContext,"Unliked" +new_like,Toast.LENGTH_SHORT).show();
holder.j = 0;
}
}
});
holder.webView.getSettings().setJavaScriptEnabled(true);
holder.webView.loadData(embed_html.get(position), "text/html", "utf-8");
Picasso.with(mContext).load(channel_thumbnail.get(position)).transform(new CircularTransform()).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(holder.chlogo);
holder.chtitle.setText(channel_title.get(position));
holder.vidtitle.setText(video_title.get(position));
holder.upld_time.setText(created_time.get(position));
int and_views = android_views.get(position);
int views = pf_views.get(position);
views += and_views;
int and_likes = android_likes.get(position);
int likes = pf_likes.get(position);
likes += and_likes;
holder.show_views.setText("" + views);
holder.show_likes.setText("" + likes);
}
#Override
public int getItemCount() {
return embed_html.size();
}
}
when i am clicking then image change for 0th postion then 4,8,12.... why onclicklistener effect every 4 object in recyclerview i am changing the image resource onClick but the images changes for 4postion, 8position
I would recommend doing it this way, first in your onBindViewHolder method add this code:
holder.mLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImage(position);
}
}
});
Then create a new method in this class only:
public void showImage(int position){
if (position == 0) {
holder.imageView.setImageResource(R.drawable.medal);
}
...
}

Categories