Problem with IndexOutOfBoundsException when enter Activity more than once - android

I have a problem, when I enter my FinalListActivity first time by clicking button in MainActivity, everything works good. But when I go back to MainActivity and then I try enter again it throws an exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: app.listazakupow, PID: 5147
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at app.listazakupow.Adapters.FinalListAdapter.onBindViewHolder(FinalListAdapter.java:44)
at app.listazakupow.Adapters.FinalListAdapter.onBindViewHolder(FinalListAdapter.java:16)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
I know it's something wrong with my int ArrayList in Adapter class but i dont know what i should do. It is this fragment:
holder.imageView.setImageResource(imagesIndex.get(position));
Can somone help me? Below my code:
FinalListActivity
public class FinalListActivity extends AppCompatActivity {
private ArrayList<String> finalListArrayList;
private ArrayList<Integer> imagesIndex;
private RecyclerView recyclerView;
private TextView textView1, textView2, textView3;
private FinalListAdapter myAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private AppDatabase appDatabase;
private static final String DATABASE_NAME = "images_base";
#SuppressLint({"WrongViewCast", "SetTextI18n"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finallist);
Intent intent = getIntent();
finalListArrayList = intent.getStringArrayListExtra("productList");
imagesIndex = intent.getIntegerArrayListExtra("imagesList");
appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DATABASE_NAME).fallbackToDestructiveMigration().build();
recyclerView = findViewById(R.id.recycler_view1);
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
for(String s:finalListArrayList) {
String category = appDatabase.daoAccess().getCategoryByKeyword(s);
String imagePath = appDatabase.daoAccess().getImagePathForCategory(category);
int id;
if(imagePath!=null) {
id = getApplicationContext().getResources().getIdentifier(imagePath, "drawable", getPackageName());
}
else{
id = getApplicationContext().getResources().getIdentifier("app_logo_black", "drawable", getPackageName());
}
imagesIndex.add(id);
}
System.out.println("FinalListArrayListSize is:" + finalListArrayList.size()+" imageIndexList is: "+imagesIndex.size());
}
});
myAdapter = new FinalListAdapter(finalListArrayList, imagesIndex, recyclerView);
recyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
textView1 = findViewById(R.id.textView1);
textView2 = findViewById(R.id.textView2);
textView3 = findViewById(R.id.textView3);
textView1.setText("Amount of products: " + finalListArrayList.size());
}
#Override
protected void onResume(){
super.onResume();
System.out.println("FinalListArrayListSize is:" + finalListArrayList.size()+" imageIndexList is: "+imagesIndex.size());
}
}
FinalListAdapter
public class FinalListAdapter extends
RecyclerView.Adapter<FinalListAdapter.MyViewHolder> {
private ArrayList<String> mDataset;
private ArrayList<Integer> imagesIndex;
private ArrayList<FinalListItem> finalListItems;
private RecyclerView recyclerView;
public FinalListAdapter(ArrayList<String> mDataset,ArrayList<Integer> imagesIndex, RecyclerView recyclerView) {
this.mDataset = mDataset;
this.imagesIndex = imagesIndex;
this.recyclerView = recyclerView;
finalListItems = new ArrayList<>();
for (String a : mDataset) {
finalListItems.add(new FinalListItem(a, false));
}
}
public ArrayList<Integer> getImagesIndex(){
return imagesIndex;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.final_list_TextView1.setText(finalListItems.get(position).getName());
holder.imageView.setImageResource(imagesIndex.get(position));
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setBackgroundResource(R.drawable.listitem_white);
if(finalListItems.get(position).isChecked){
holder.linearLayout.setBackgroundResource(R.drawable.listitem_green);
holder.checkBox.setChecked(true);
}
else{
holder.linearLayout.setBackgroundResource(R.drawable.listitem_white);
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int currentPosition = holder.getAdapterPosition();
if(isChecked){
FinalListItem finalItemBefore = finalListItems.get(currentPosition);
FinalListItem finalItemAfter = new FinalListItem(finalItemBefore.getName(), true);
finalListItems.remove(finalItemBefore);
finalListItems.add(finalItemAfter);
recyclerView.scrollToPosition(0);
holder.linearLayout.setBackgroundResource(R.drawable.listitem_green);
notifyItemMoved(currentPosition, getItemCount() - 1);
}
else{
finalListItems.get(currentPosition).setChecked(false);
notifyItemChanged(currentPosition);
}
}
});
}
#Override
public int getItemCount() {
return finalListItems.size();
}
private class FinalListItem {
private String name;
private boolean isChecked;
public FinalListItem(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getName() {
return name;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
final private TextView final_list_TextView1;
final private CheckBox checkBox;
final private LinearLayout linearLayout;
final private ImageView imageView;
public MyViewHolder(View view) {
super(view);
final_list_TextView1 = view.findViewById(R.id.final_list_TextView1);
checkBox = view.findViewById(R.id.checkBox1);
linearLayout = view.findViewById(R.id.linearLayout1);
imageView = view.findViewById(R.id.item_image);
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.finallist_list_layout, parent, false);
return new MyViewHolder(view);
}
}

Yes, the line of code:
holder.imageView.setImageResource(imagesIndex.get(position));
is causing the error.
Why? Because the value of position has nothing to do with the index of any value in the ArrayList "imagesIndex". The value position you get from onBindViewHolder refers to the row in the RecyclerView that means the ArrayList "finalListItems" which you generate in your constructor.

Related

ItemView.setOnCLickListiner is Being Ignored and does not get clicked when it is clicked

please can anyone help me fix this my itemview is not being clicked wen i click it in my fragment after implementing my onItemClickListener interface in my adapter, i also called the adapter in my fragment but if i run the app and i click d cardview nothing happens and am using list adapter which extends recyclerView. please if anyone can help me i will b grateful
my adapter
public class Apiary_Adapter extends ListAdapter<RecordModel,Apiary_Adapter.ApiaryHolder> {
Apiaries apiaries;
Context context;
RecordOnClickListener listener;
public RecordViewModel record_View_model = Apiaries.record_View_model;
public Apiary_Adapter(Apiaries apiaries, Context context ) {
super(DIFF_CALLBACK);
this.apiaries = apiaries;
this.context = context;
}
private static final DiffUtil.ItemCallback<RecordModel> DIFF_CALLBACK = new DiffUtil.ItemCallback<RecordModel>() {
#Override
public boolean areItemsTheSame(#NonNull RecordModel oldItem, #NonNull RecordModel newItem) {
return oldItem.getId() == newItem.getId();
}
#Override
public boolean areContentsTheSame(#NonNull RecordModel oldItem, #NonNull RecordModel newItem) {
return oldItem.getAddress().equals(newItem.getAddress())&&oldItem.getApiaryNo().equals(newItem.getApiaryNo())
&&oldItem.getTown().equals(newItem.getTown())&&oldItem.getApiaryLongitude().equals(newItem.getApiaryLongitude())
&&oldItem.getApiaryLatitude().equals(newItem.getApiaryLatitude())&&oldItem.getDateOfHarvest().equals(newItem.getDateOfHarvest())
&&oldItem.getDateOfColonisation().equals(newItem.getDateOfColonisation())&&oldItem.getNoOfWaxHarvested().equals(newItem.getNoOfWaxHarvested())
&&oldItem.getQuantityOfHoneyHarvested().equals(newItem.getQuantityOfHoneyHarvested())&&oldItem.getNoOfPropolis().equals(newItem.getNoOfPropolis())
&&oldItem.getNoOfCombs().equals(newItem.getNoOfCombs())&&oldItem.getHiveNo().equals(newItem.getHiveNo())
&&oldItem.getHiveLongitude().equals(newItem.getHiveLongitude())&&oldItem.getHiveLatitude().equals(newItem.getHiveLatitude())
&&oldItem.getTime().equals(newItem.getTime())&&oldItem.getDate().equals(newItem.getDate());
}
};
public class ApiaryHolder extends RecyclerView.ViewHolder {
private TextView address;
private TextView apiary;
private TextView town;
private TextView LocationLatitude;
private TextView LocationLongitude;
private TextView HiveLatitude;
private TextView HiveLongitude;
private TextView date;
private TextView time;
private TextView hiveNo;
private TextView noOfComb;
private TextView dateOfHarvest;
private TextView dateOfColonisation;
private TextView waxHarvested;
private TextView quantityOfhoney;
private TextView noOfPropolis;
private CheckBox checkBox;
CardView cardView;
Apiaries apiaries;
public ApiaryHolder(#NonNull final View itemView, final Apiaries apiaries) {
super(itemView);
address = itemView.findViewById(R.id.customAddress);
apiary = itemView.findViewById(R.id.customApiaryNo);
town = itemView.findViewById(R.id.customTown);
LocationLongitude = itemView.findViewById(R.id.customLongitude);
LocationLatitude = itemView.findViewById(R.id.customLatitude);
checkBox = itemView.findViewById(R.id.customCheckbox);
hiveNo = itemView.findViewById(R.id.customHiveNo);
noOfComb = itemView.findViewById(R.id.customCombNo);
dateOfHarvest = itemView.findViewById(R.id.customDateOfHarvest);
dateOfColonisation = itemView.findViewById(R.id.customDateOfColonisation);
waxHarvested = itemView.findViewById(R.id.customNoOfWaxHarveted);
quantityOfhoney = itemView.findViewById(R.id.customQuantityOfHoney);
noOfPropolis = itemView.findViewById(R.id.customNoOfPropolis);
HiveLatitude = itemView.findViewById(R.id.customHiveLatitude);
HiveLongitude = itemView.findViewById(R.id.customHiveLongitude);
date = itemView.findViewById(R.id.customDate);
time = itemView.findViewById(R.id.customTime);
cardView = itemView.findViewById(R.id.Cardview);
this.apiaries = apiaries;
mainActivity = new MainActivity();
cardView.setOnLongClickListener(apiaries);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Position = getAdapterPosition();
if (listener != null && Position != RecyclerView.NO_POSITION){
listener.OnItemClick(getItem(Position));
Toast.makeText(context, "Hello9", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
}
});
}
#NonNull
#Override
public ApiaryHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customlayout, parent, false);
final ApiaryHolder apiaryHolder= new ApiaryHolder(itemView, apiaries);
return apiaryHolder;
}
#Override
public void onBindViewHolder(#NonNull ApiaryHolder holder, final int position) {
RecordModel currentRecord = getItem(position);
holder.address.setText(currentRecord.getAddress());
holder.apiary.setText(currentRecord.getApiaryNo());
holder.town.setText(currentRecord.getTown());
holder.LocationLatitude.setText(currentRecord.getApiaryLatitude());
holder.LocationLongitude.setText(currentRecord.getApiaryLongitude());
holder.hiveNo.setText(currentRecord.getHiveNo());
holder.noOfComb.setText(currentRecord.getNoOfCombs());
holder.dateOfHarvest.setText(currentRecord.getDateOfHarvest());
holder.dateOfColonisation.setText(currentRecord.getDateOfColonisation());
holder.waxHarvested.setText(currentRecord.getNoOfWaxHarvested());
holder.quantityOfhoney.setText(currentRecord.getQuantityOfHoneyHarvested());
holder.noOfPropolis.setText(currentRecord.getNoOfPropolis());
holder.HiveLatitude.setText(currentRecord.getHiveLatitude());
holder.HiveLongitude.setText(currentRecord.getHiveLongitude());
holder.date.setText(currentRecord.getDate());
holder.time.setText(currentRecord.getTime());
}
public interface RecordOnClickListener{
void OnItemClick(RecordModel recordModel);
}
public void setOnItemClickListener(RecordOnClickListener listener){
this.listener = listener;
}
my fragment
public class Apiaries extends Fragment implements View.OnLongClickListener {
public static boolean is_in_contextualMode = false;
public static RecordViewModel record_View_model;
Apiary_Adapter apiary_adapter;
public static int counter = 0;
public static ArrayList<RecordModel> selectionList =new ArrayList<>();
private RecyclerView recyclerView;
public static SearchView searchView;
public static final int ADD_RECORD_REQUEST = 1;
public static final int EDIT_RECORD_REQUEST = 2;
com.github.clans.fab.FloatingActionButton floatingActionButton;
FirebaseAuth firebaseAuth;
DatabaseReference reference;
public static MainActivity mainActivity;
private Menu menu;
ArrayList<RecordModel> list = new ArrayList<>();
public Apiaries() {
// Required empty public constructor
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_apiaries, container, false);
floatingActionButton = (FloatingActionButton) view.findViewById(R.id.fab2);
Apiaries apiaries = new Apiaries();
apiary_adapter = new Apiary_Adapter(apiaries, getActivity());
firebaseAuth = FirebaseAuth.getInstance();
String currentUserId = firebaseAuth.getCurrentUser().getUid();
reference = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserId);
recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(apiary_adapter);
recyclerView.setHasFixedSize(true);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainActivity = new MainActivity();
record_View_model = new ViewModelProvider(getActivity()).get(RecordViewModel.class);
record_View_model.getAllRecord().observe(getActivity(), new Observer<List<RecordModel>>() {
#Override
public void onChanged(#Nullable List<RecordModel> recordModels) {
apiary_adapter.submitList(recordModels);
}
});
apiary_adapter.setOnItemClickListener(new Apiary_Adapter.RecordOnClickListener() {
#Override
public void OnItemClick(RecordModel recordModel) {
Intent intent = new Intent(getContext(), EditApiaryAddActivity.class);
intent .putExtra(EditApiaryAddActivity.EXTRA_ID, recordModel.getId());
intent .putExtra(EditApiaryAddActivity.EXTRA_ADDRESS, recordModel.getAddress());
intent .putExtra(EditApiaryAddActivity.EXTRA_APIARYNAME, recordModel.getApiaryNo());
intent .putExtra(EditApiaryAddActivity.EXTRA_TOWN, recordModel.getTown());
intent .putExtra(EditApiaryAddActivity.EXTRA_LOCATION_LATITUDE, recordModel.getApiaryLatitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_LOCATION_LONGITUDE, recordModel.getApiaryLongitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_HIVE_LATITUDE, recordModel.getHiveLatitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_HIVE_LONGITUDE, recordModel.getHiveLongitude());
intent.putExtra(EditApiaryAddActivity.EXTRA_HIVENO, recordModel.getHiveNo());
intent.putExtra(EditApiaryAddActivity.EXTRA_NOOFCOMBS, recordModel.getNoOfCombs());
intent.putExtra(EditApiaryAddActivity.EXTRA_DATEOFHARVEST, recordModel.getNoOfWaxHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_DATEOFCOLONISATION, recordModel.getDateOfColonisation());
intent.putExtra(EditApiaryAddActivity.EXTRA_WAXHARVESTED, recordModel.getNoOfWaxHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_QUANTITYOFHONEY, recordModel.getQuantityOfHoneyHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_NOOFPROPOLIS, recordModel.getNoOfPropolis());
startActivityForResult(intent,EDIT_RECORD_REQUEST);
Apiaries.is_in_contextualMode = false;
mainActivity.clearActionMode();
}
});
}
#Override
public boolean onLongClick(View v) {
MainActivity.toolbar.getMenu().clear();
MainActivity.toolbar.inflateMenu(R.menu.menu_record);
MainActivity.textView1.setVisibility(View.GONE);
MainActivity.itemCountTextView.setVisibility(View.VISIBLE);
MainActivity.edit.setVisibility(View.VISIBLE);
is_in_contextualMode = true;
return true;
}
You should handle Clicks in the onCreateViewHolder method
public ApiaryHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customlayout, parent, false);
final ApiaryHolder apiaryHolder= new ApiaryHolder(itemView, apiaries);
ApiaryHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle the clicks here
}
}
});
return apiaryHolder;
}
You have implemented onLongClickListener Instead of onClickListener
Add the onClickListener Inside on bindviewholder Like holder.itemView.setOnClickLstener

why does isChecked() method not working with my array

So my problem is that.. why does the isChecked method not working.
My first guess to my problem would be im declaring the wrong array?
My second guess would be I lack something to call or missing something out?
the goal of my code here is to create a collector in firebase and then record it in the database of the collector by which the user chose from the multiple selected job orders
public class MainActivity extends AppCompatActivity {
private List<Model> mModelList;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
Button mjobOrderBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String jobId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerview);
mjobOrderBtn = findViewById(R.id.jobOrderBtn);
mRecyclerView = findViewById(R.id.recycler_view);
mAdapter = new RecyclerViewAdapter(getListData());
LinearLayoutManager manager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(manager);
mRecyclerView.setAdapter(mAdapter);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
jobId = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("job order").document(jobId);
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRecyclerView.isChecked()){
}
}
});
}
private List<Model> getListData() {
mModelList = new ArrayList<>();
mModelList.add(new Model("Flat Tire "));
mModelList.add(new Model("Towing "));
mModelList.add(new Model("Battery "));
mModelList.add(new Model("Empty Gas "));
return mModelList;
}
}
RecyclerViewAdaptor.java
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private List<Model> mModelList;
public RecyclerViewAdapter(List<Model> modelList) {
mModelList = modelList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itemrow, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Model model = mModelList.get(position);
holder.textView.setText(model.getText());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setSelected(!model.isSelected());
holder.view.setBackgroundColor(model.isSelected() ? Color.CYAN : Color.WHITE);
}
});
}
#Override
public int getItemCount() {
return mModelList == null ? 0 : mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private View view;
private TextView textView;
private MyViewHolder(View itemView) {
super(itemView);
view = itemView;
textView = itemView.findViewById(R.id.text_view);
}
}
}
Also here's the model class
Model.java
public class Model {
private String text;
private boolean isSelected = false;
public Model(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
}
you need to create checkbox inside view item layout for each item in your array. Here is an example
you can get your order list with a defined method inside adapter class. Something like this:
public List<Model> getSelectedItems(){
List<Model> results = new ArrayList<Model>();
for(model: mModelList){
if(model.isSelected()){
results.add(model);
}
}
return results;
}
And inside button order click method, just get it out:
mjobOrderBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<Model> orderList = mAdapter.getSelectedItems();
}
});

Retrieving data inside of RecyclerView

I want to create this card view inside recycler View.
I got this problem.I can't retrieve the data inside of the card views.
I want to whenever that Check Box is true, Get the data(Meal, price, and count which is in this example (1)) and add to the list in my Main Activity.
I am stuck on this for 6 hour straight. If someone know the solution please help. I am dying over here.
MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
CardData data;
List<CardData> list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Hawk.init(getApplicationContext()).build();
data = new CardData("Meal","1","12","http");
list.add(data);
recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
final RecyclerView.Adapter adapter=new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<CardData> data;
private Context context;
public MyAdapter(Context context,List<CardData> data){
this.data=data;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_contents,viewGroup,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {
myViewHolder.Meal.setText(data.get(i).Yemek);
myViewHolder.price.setText(data.get(i).Qiymet);
//Glide.with(context).load(data.get(i).url).into(myViewHolder.img);
myViewHolder.count.getText();
myViewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myViewHolder.checkBox.setChecked(!myViewHolder.checkBox.isChecked());
data.get(i).checked = myViewHolder.checkBox.isChecked();
}
});
myViewHolder.add.setFocusable(true);
myViewHolder.remove.setFocusable(true);
myViewHolder.add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String countS = myViewHolder.count.getText().toString();
int countI = Integer.valueOf(countS);
countI += 1;
String countN = String.valueOf(countI);
myViewHolder.count.setText(countN);
}
});
myViewHolder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String sayS = myViewHolder.count.getText().toString();
int sayI = Integer.valueOf(sayS);
if (sayI>0){
sayI -= 1;}
String sayN = String.valueOf(sayI);
myViewHolder.count.setText(sayN);
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Meal;
TextView price;
TextView count;
CardView card;
ImageView img;
CheckBox checkBox;
Button add;
Button remove;
MyViewHolder(View view){
super(view);
this.Meal = (TextView) view.findViewById(R.id.Meal);
this.price = (TextView) view.findViewById(R.id.Cost);
this.count = (TextView) view.findViewById(R.id.Count);
this.add = (Button) view.findViewById(R.id.addButton);
this.remove = (Button) view.findViewById(R.id.removeButton);
this.checkBox = (CheckBox) view.findViewById(R.id.checkBox);
this.img = (ImageView) view.findViewById(R.id.img);
this.card = (CardView) view.findViewById(R.id.card_view);
}
}
}
Data:
public class CardData {
public CardData() {
}
public String Meal;
public String Portion;
public String Cost;
public String url;
public Boolean checked;
public CardData(String meal, String portion, String cost, String url) {
Meal = meal;
Portion = portion;
Cost = cost;
this.url = url;
}
public Boolean isChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public String getMeal() {
return Meal;
}
public void setMeal(String meal) {
Meal = meal;
}
public String getPortion() {
return Portion;
}
public void setPortion(String portion) {
Portion = portion;
}
public String getCost() {
return Cost;
}
public void setCost(String cost) {
Cost = cost;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}

Data from Firebase won't show on my RecyclerView with CardView

I'm trying to display the data from my Firebase but it won't display to my recyclerView. I don't know what was wrong.
I'm also trying to find some tutorials or the same question from stackoverflow but I don't get it. Still don't show the data from Firebase.
HistoryActivity.class
public class HistoryActivity extends AppCompatActivity {
String name, route;
int earnings, time, distance, totalPassenger, tripCount;
private Firebase ref;
private RecyclerView recycler;
private RecyclerViewAdapter adapter;
List<History> historyList;
History history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
Firebase.setAndroidContext(this);
recycler = (RecyclerView) findViewById(R.id.recyclerview);
historyList = fillData();
recycler.setLayoutManager(new LinearLayoutManager(this));
}
public List<History> fillData() {
historyList = new ArrayList<>();
ref = new Firebase(Config.FIREBASE_URL_HISTORY_DRIVER);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(HistoryActivity.this, snapshot.getValue()+"", Toast.LENGTH_SHORT).show();
name = snapshot.child("driverName").getValue().toString().trim();
route = snapshot.child("destination").getValue().toString().trim();
earnings = Integer.valueOf(snapshot.child("earnings").getValue().toString().trim());
time = Integer.valueOf(snapshot.child("time").getValue().toString().trim());
distance = Integer.valueOf(snapshot.child("distanceTravelled").getValue().toString().trim());
totalPassenger = Integer.valueOf(snapshot.child("totalPassenger").getValue().toString().trim());
tripCount = Integer.valueOf(snapshot.child("tripCount").getValue().toString().trim());
historyList.add(new History(name, route, earnings, time, distance, totalPassenger, tripCount));
}
Toast.makeText(HistoryActivity.this, historyList.size()+":size", Toast.LENGTH_LONG).show();
adapter = new RecyclerViewAdapter(historyList);
recycler.setAdapter(adapter);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return historyList;
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder> {
List<History> historyList;
Context context;
public RecyclerViewAdapter(List<History> historyList) {
this.historyList = historyList;
}
#Override
public HistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflate the layout, initialize the View Holder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_layout, parent, false);
HistoryViewHolder holder = new HistoryViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.HistoryViewHolder holder, int position) {
holder.driversName.setText(historyList.get(position).getDriversName());
holder.route.setText(historyList.get(position).getRoute());
holder.totalEarnings.setText(historyList.get(position).getEarnings());
holder.time.setText(historyList.get(position).getTime());
holder.distance.setText(historyList.get(position).getDistance());
holder.totalPassenger.setText(historyList.get(position).getTotalPassenger());
holder.tripCount.setText(historyList.get(position).getTripCount());
animate(holder);
}
#Override
public int getItemCount() {
return historyList.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void animate(RecyclerView.ViewHolder viewHolder) {
final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(context, R.anim.bounce_interpolator);
viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}
public static class HistoryViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
EditText driversName;
EditText route;
EditText totalEarnings;
EditText time;
EditText distance;
EditText totalPassenger;
EditText tripCount;
public HistoryViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cardView);
driversName = (EditText) itemView.findViewById(R.id.edtDriversName);
route = (EditText) itemView.findViewById(R.id.edtRoute);
totalEarnings = (EditText) itemView.findViewById(R.id.edtEarning);
time = (EditText) itemView.findViewById(R.id.edtTime);
distance = (EditText) itemView.findViewById(R.id.edtDistance);
totalPassenger = (EditText) itemView.findViewById(R.id.edtTotalPass);
tripCount = (EditText) itemView.findViewById(R.id.edtTripCount);
}
}
}
History(pojo)
public class History {
private String username;
private String driversName;
private String route;
private int earnings;
private int time;
private int distance;
private int totalPassenger;
private int tripCount;
public History(String driversName, String route, int earnings, int time, int distance, int totalPassenger, int tripCount) {
this.driversName = driversName;
this.route = route;
this.earnings = earnings;
this.time = time;
this.distance = distance;
this.totalPassenger = totalPassenger;
this.tripCount = tripCount;
}
You need to set layout before setting adapter like this:
recycler = (RecyclerView) findViewById(R.id.recyclerview);
recycler.setLayoutManager(new LinearLayoutManager(this));
historyList = fillData();

RecyclerView is showing nothing

I have some items in my adapter but nothing is shown in the RecyclerView.
Adapter
public class WorkOrderAdapter extends RecyclerView.Adapter<WorkOrderViewHolder> {
private List<WorkOrder> orders = new LinkedList<>();
public void setData(List<WorkOrder> orders) {
this.orders = orders;
}
#Override
public WorkOrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_workorder, parent, false);
return new WorkOrderViewHolder(view);
}
#Override
public void onBindViewHolder(WorkOrderViewHolder holder, int position) {
WorkOrder order = orders.get(position);
holder.bind(order);
}
#Override
public int getItemCount() {
return orders.size();
}
}
ViewHolder
public class WorkOrderViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView description;
private TextView date;
public WorkOrderViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title_textview);
description = (TextView) view.findViewById(R.id.description_textview);
date = (TextView) view.findViewById(R.id.date_textview);
}
public void bind(WorkOrder order) {
title.setText("Test");
description.setText("Test");
date.setText("Test");
}
}
Activity (Using AndroidAnnotations)
#EActivity(R.layout.activity_workorders)
#OptionsMenu(R.menu.activity_workorders)
public class WorkOrdersActivity extends ToolbarActivity {
#ViewById(R.id.orders_recyclerview)
RecyclerView ordersList;
List<WorkOrder> orders = new LinkedList<>();
private WorkOrderAdapter adapter;
{
adapter = new WorkOrderAdapter();
orders.add(new WorkOrder());
orders.add(new WorkOrder());
orders.add(new WorkOrder());
adapter.setData(orders);
}
#AfterViews
public void initViews() {
ordersList.setAdapter(adapter);
}
}
Please add the LayoutManager to the RecyclerView and try again
ordersList.setLayoutManager(new LinearLayoutManager(this));
ordersList.setAdapter(adapter);

Categories

Resources