RecyclerView: incorrect binding when items are recycled - android-recyclerview

Each item in my RecyclerView consists of 4 EditTexts.
As long as no item is recycled, my app can change the text in any of these EditTexts.
However, as soon as items are recycled, only the first (I mean the leftmost) Edittext in the item can be updated correctly, whatever the selection.
Any idea of what could go wrong?
This is the top of the stack:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: be.ema.moles, PID: 8968
java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.recyclerview.widget.RecyclerView$ViewHolder.getAdapterPosition()' on a null object reference
at androidx.recyclerview.selection.StableIdKeyProvider.onDetached(StableIdKeyProvider.java:90)
at androidx.recyclerview.selection.StableIdKeyProvider$1.onChildViewDetachedFromWindow(StableIdKeyProvider.java:69)
at androidx.recyclerview.widget.RecyclerView.dispatchChildDetached(RecyclerView.java:7261)
at androidx.recyclerview.widget.RecyclerView.removeDetachedView(RecyclerView.java:4139)
at androidx.recyclerview.widget.RecyclerView$LayoutManager.removeAndRecycleScrapInt(RecyclerView.java:8978)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep3(RecyclerView.java:3997)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3652)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
at android.view.View.layout(View.java:20672)
...
Here is the Fragment controlling the contents of the RecyclerView
public class MoleFragment extends Fragment {
RecyclerView moleRecycler = null;
TextView addBtn = null;
Cursor moleCursor = null;
static int moleAdapterPosition = 0;
static String moleId = "";
static String contactId = "";
static String rawContactId = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.moles_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Cursor moleCursor = readMoles();
moleRecycler = (RecyclerView) getActivity().findViewById(R.id.moles);
moleRecycler.setHasFixedSize(true);
moleRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
moleRecycler.setAdapter(new MolesCursorAdapter(getActivity(), moleCursor));
OnItemActivatedListener<Long> moleItemActivatedListener = new OnItemActivatedListener() {
#Override
public boolean onItemActivated(#NonNull ItemDetailsLookup.ItemDetails item, #NonNull MotionEvent e) {
moleAdapterPosition = item.getPosition();
moleCursor.moveToPosition(item.getPosition());
moleId = Long.toString(moleCursor.getLong(0));
return true;
}
};
SelectionTracker moleTracker = new SelectionTracker.Builder<Long>("selectedMoleId",
moleRecycler,
new StableIdKeyProvider(moleRecycler),
new MoleDetailsLookup(),
StorageStrategy.createLongStorage())
.withSelectionPredicate(SelectionPredicates.<Long>createSelectSingleAnything())
.withOnItemActivatedListener(moleItemActivatedListener)
.build();
return ;
}
public Cursor readMoles() {
String[] contactIds = getShownCustomer();
String selection = Data.RAW_CONTACT_ID + "=? AND " + Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?";
String[] selectionArgs = new String[]{contactIds[0], contactIds[1], MOLE_MIME_TYPE};
return moleCursor = getActivity().getContentResolver().query(
Data.CONTENT_URI,
new String[] {
Data._ID,
Data.DATA1,
Data.DATA2,
Data.DATA3,
Data.DATA4},
selection,
selectionArgs,
null
);
}
/**
* Create a new instance of DetailsFragment, initialized to
* show the catches for customer 'contactId'.
*/
public static MoleFragment newInstance(String rawContactId, String contactId) {
MoleFragment f = new MoleFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putString("rawContactId", rawContactId);
args.putString("contactId", contactId);
f.setArguments(args);
return f;
}
public String[] getShownCustomer() {
rawContactId = getArguments().getString("rawContactId", "");
contactId = getArguments().getString("contactId", "");
String[] contactIds = new String[2];
contactIds[0] = getArguments().getString("rawContactId", "");
contactIds[1] = getArguments().getString("contactId", "");
return contactIds;
}
private class MoleDetailsLookup extends ItemDetailsLookup<Long> {
#Nullable
#Override
public ItemDetails<Long> getItemDetails(#NonNull MotionEvent event) {
View view = moleRecycler.findChildViewUnder(event.getX(), event.getY());
if (view != null) {
final RecyclerView.ViewHolder viewHolder = moleRecycler.getChildViewHolder(view);
if (viewHolder instanceof MolesCursorAdapter.ViewHolder) {
final MolesCursorAdapter.ViewHolder moleViewHolder = (MolesCursorAdapter.ViewHolder) viewHolder;
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return viewHolder.getAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return Long.valueOf(moleViewHolder.position);
}
};
}
}
return null;
}
}
}
And this is the RecyclerView.Adapater
public class MolesCursorAdapter extends RecyclerView.Adapter<MolesCursorAdapter.ViewHolder> {
private CursorAdapter mCursorAdapter;
private Context mContext;
private ViewHolder holder;
public MolesCursorAdapter(Context context, Cursor c) {
mContext = context;
mCursorAdapter = new CursorAdapter(mContext, c, 0) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.moles, parent, false);
return v;
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
String s = cursor.getString(1);
if (s != null) {
holder.startDate.setText(s.substring(6, 8) + "/" + s.substring(4, 6) + "/" + s.substring(0, 4));
} else {
holder.startDate.setText("");
}
s = cursor.getString(2);
if (s != null) {
s = s.substring(6,8) + "/" + s.substring(4,6) + "/" + s.substring(0,4);
holder.endDate.setText(s);
} else {
holder.endDate.setText("");
}
holder.round.setText(cursor.getString(3));
holder.moleType.setText(cursor.getString(4));
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder implements TextWatcher {
public int position;
public EditText startDate;
public EditText endDate;
public EditText round;
public EditText moleType;
public TextView deleteBtn;
public ViewHolder(View itemView) {
super(itemView);
startDate = (EditText) itemView.findViewById(R.id.startDate);
endDate = (EditText) itemView.findViewById(R.id.endDate);
round = (EditText) itemView.findViewById(R.id.round);
moleType = (EditText) itemView.findViewById(R.id.moleType);
deleteBtn = (TextView) itemView.findViewById(R.id.deleteBtn);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String value = s.toString();
ContentValues newValues = new ContentValues();
if (TextUtils.isDigitsOnly(s)) {
newValues.put(ContactsContract.Data.DATA3, value);
} else {
newValues.put(ContactsContract.Data.DATA4, value);
}
updateRepository(newValues);
}
}
#Override
public int getItemCount() {
return mCursorAdapter.getCount();
}
#Override
public long getItemId(int position) {
return Long.valueOf(position);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// Passing the binding operation to cursor loader
mCursorAdapter.getCursor().moveToPosition(position);
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextWatcher tw = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String value = s.toString();
ContentValues newValues = new ContentValues();
if (TextUtils.isDigitsOnly(s)) {
newValues.put(ContactsContract.Data.DATA3, value);
} else {
newValues.put(ContactsContract.Data.DATA4, value);
}
updateRepository(newValues);
}
};
View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
holder = new ViewHolder(v);
holder.startDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
// business logic
}
});
holder.endDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
// business logic
}
});
holder.round.addTextChangedListener(tw);
holder.moleType.addTextChangedListener(tw);
holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String selectionClause = ContactsContract.Data._ID + "=?";
String[] selectionArgs = new String[] {mCursorAdapter.getCursor().getString(0)};
int rowsDeleted = mContext.getContentResolver().delete(
ContactsContract.Data.CONTENT_URI,
selectionClause,
selectionArgs
);
}
});
return holder;
}
}

Instead of adding a ClickListener on each View in the ViewHolder in the onCreateViewHolder method, I have added a unique tag on each View. This unique tag is used in a general (I mean at Class level) ClickListener to perform the business logic:
public class MolesCursorAdapter3 extends RecyclerView.Adapter<MolesCursorAdapter3.MolesViewHolder> {
private CursorAdapter mCursorAdapter;
private Context mContext;
public ConstraintLayout holder;
public EditText startDate;
public EditText endDate;
public EditText round;
public EditText moleType;
public TextView deleteBtn;
public class MolesViewHolder extends RecyclerView.ViewHolder implements TextWatcher, View.OnClickListener {
public int position;
public String vhMoledId = "";
public MolesViewHolder(ConstraintLayout itemView) {
super(itemView);
holder = itemView;
startDate = (EditText) itemView.findViewById(R.id.startDate);
startDate.setOnClickListener(this);
endDate = (EditText) itemView.findViewById(R.id.endDate);
endDate.setOnClickListener(this);
round = (EditText) itemView.findViewById(R.id.round);
round.addTextChangedListener(this);
moleType = (EditText) itemView.findViewById(R.id.moleType);
moleType.addTextChangedListener(this);
deleteBtn = (TextView) itemView.findViewById(R.id.deleteBtn);
deleteBtn.setOnClickListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String value = s.toString();
ContentValues newValues = new ContentValues();
if (TextUtils.isDigitsOnly(s)) {
newValues.put(ContactsContract.Data.DATA3, value);
} else {
newValues.put(ContactsContract.Data.DATA4, value);
}
updateRepository(newValues, vhMoledId);
}
#Override
public void onClick(final View v) {
String tag = (String) v.getTag();
String viewTag = tag.substring(0, 3);
final String moleId = tag.substring(3);
switch (viewTag) {
case "del":
// business logic
break;
case "sta":
ConstraintLayout vh = (ConstraintLayout) v.getParent();
endDate = vh.findViewWithTag("end" + moleId);
// business logic
break;
case "end":
vh = (ConstraintLayout) v.getParent();
startDate = vh.findViewWithTag("sta" + moleId);
// business logic
break;
}
}
}
public MolesCursorAdapter3(Context context, Cursor c) {
mContext = context;
mCursorAdapter = new CursorAdapter(mContext, c, 0) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.moles, parent, false);
return v;
}
#Override
public void bindView(View itemView, final Context context, final Cursor cursor) {
ConstraintLayout vh = (ConstraintLayout) itemView;
String moleId = cursor.getString(0);
startDate = (EditText) vh.findViewById(R.id.startDate);
startDate.setTag("sta" + moleId);
endDate = (EditText) vh.findViewById(R.id.endDate);
endDate.setTag("end" + moleId);
round = (EditText) vh.findViewById(R.id.round);
moleType = (EditText) vh.findViewById(R.id.moleType);
deleteBtn = (TextView) vh.findViewById(R.id.deleteBtn);
deleteBtn.setTag("del" + moleId);
String s = cursor.getString(1);
if (s != null) {
startDate.setText(s.substring(6, 8) + "/" + s.substring(4, 6) + "/" + s.substring(0, 4));
} else {
startDate.setText("");
}
s = cursor.getString(2);
if (s != null) {
s = s.substring(6,8) + "/" + s.substring(4,6) + "/" + s.substring(0,4);
endDate.setText(s);
} else {
endDate.setText("");
}
round.setText(cursor.getString(3));
moleType.setText(cursor.getString(4));
}
};
}
#Override
public MolesCursorAdapter3.MolesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ConstraintLayout molesLayout = (ConstraintLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.moles, parent, false);
MolesViewHolder vh = new MolesViewHolder(molesLayout);
return vh;
}
#Override
public void onBindViewHolder(#NonNull MolesViewHolder holder, int position) {
// Passing the binding operation to cursor loader
mCursorAdapter.getCursor().moveToPosition(position);
mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());
holder.vhMoledId = mCursorAdapter.getCursor().getString(0);
holder.position = position;
}
#Override
public int getItemCount() {
return mCursorAdapter.getCount();
}
#Override
public long getItemId(int position) {
return Long.valueOf(position);
}
public void updateRepository(ContentValues newValues, String moleId) {
final String selection = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.Data._ID + " = ?";
final String[] selectionArgs = new String[]{MOLE_MIME_TYPE, moleId};
int rowsUpdated = mContext.getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
newValues,
selection,
selectionArgs
);
}
}

Related

Delete duplicates items from my ArrayList of MyModel

I tried everything to remove the elements from my array without losing the json data of my SharedPreferences, if I don't add in my HashSet the data that I merged, I get an array without duplicate elements. This is what I want, add my model element without duplications in my array by loading the elements from the Json.
**Here my MyModel :**
public class MyModel {
Integer imageRes;
String textRes;
public MyModel(Integer imageRes, String textRes) {
this.imageRes = imageRes;
this.textRes = textRes;
}
public Integer getImageRes() {
return imageRes;
}
public void setImageRes(Integer imageRes) {
this.imageRes = imageRes;
}
public String getTextRes() {
return textRes;
}
public void setTextRes(String textRes) {
this.textRes = textRes;
}
}
And here my Holder
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myViewHolder> {
public MyAdapter(ArrayList<MyModel> models) {
this.models = models;
}
private final ArrayList<MyModel> models;
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent,false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
holder.setIsRecyclable(false);
holder.imageItem.setImageResource(models.get(position).getImageRes());
holder.textItem.setText(models.get(position).getTextRes());
}
public ArrayList<MyModel> getModels() {
return models;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return (models == null) ? 0 : models.size();
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
}
static class myViewHolder extends RecyclerView.ViewHolder{
ImageView imageItem;
TextView textItem;
public myViewHolder(#NonNull View itemView){
super(itemView);
imageItem = itemView.findViewById(R.id.ItemMarker);
textItem = itemView.findViewById(R.id.itemTxt);
}
}
}
**And here my problem :**
if(models != null){
try {
try{
SharedPreferences ListDatas = getSharedPreferences("SavedList", MODE_PRIVATE);
Gson gson = new Gson();
String json = ListDatas.getString("ListKey", null);
Type type = new TypeToken<ArrayList<MyModel>>(){}.getType();
models = gson.fromJson(json, type);
list.setHasFixedSize(true);
if(adapter != null){
adapter.setHasStableIds(true);
}
list.setAdapter(adapter);
list.setBackgroundColor(R.color.items);
list.setDuplicateParentStateEnabled(false);
models.ensureCapacity(100);
adapter = new MyAdapter(models);
NewModel = models;
Set<MyModel> DelItems = new HashSet<>();
DelItems.add(new MyModel(R.drawable.marker, "Commande en cours..." + "\n" + "Date : " + dateFormat + "\n" + "Nettoyage enregistré à : " + heure + "H" + minutes));
Set<MyModel> DelItems2 = new HashSet<>(NewModel);
NewModel.clear();
Set<MyModel> DelItemsFinal = new HashSet<>(DelItems2);
DelItemsFinal.addAll(DelItems2);
DelItemsFinal.addAll(DelItems);
Set<MyModel> DelItemsFinal2 = new LinkedHashSet<>(DelItemsFinal);
NewModel.clear();
NewModel.addAll(DelItemsFinal2);
DelItems.clear();
DelItems2.clear();
adapter.notifyDataSetChanged();
lastPosition = NewModel.size() -1;
layoutManager.scrollToPosition(lastPosition);
InfosHisto.setText("Votre historique de commande");
} catch (JsonSyntaxException e) {
e.printStackTrace();
}

How to implement an Action on Item Click in Order to show the result in CardView of RecyclerView

I am very new to Android programming. I can't find a solution for my current problem which I've been trying to solve for days.
I want to click on item of populated Array List and get the position i.e. the searched word result in Cardview (neither ItemClickListener nor OnSuggestionListener did work here. Here is my code of MainActivity and I would be very thankful if somebody could help me out:
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
SearchAdapter adapter;
MaterialSearchBar materialSearchBar;
List<String> suggestList = new ArrayList<>();
Database database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//init View
recyclerView = (RecyclerView) findViewById(R.id.recycler_search);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = (MaterialSearchBar) findViewById(R.id.search_bar);
database = new Database(this);
materialSearchBar.setHint("Search");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener (new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
List<String> suggest = new ArrayList<>();
for (String search : suggestList) {
if (search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener (new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled)
adapter = new SearchAdapter(getBaseContext(), database.getLughats());
recyclerView.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
adapter = new SearchAdapter(this, database.getLughats());
recyclerView.setAdapter(adapter);
}
private void startSearch(String text) {
adapter = new SearchAdapter(this, database.getLughatByWort(text));
recyclerView.setAdapter(adapter);
}
private void loadSuggestList() {
suggestList = database.getWorts();
materialSearchBar.setLastSuggestions(suggestList);
}
}```
Let me know if I should post here also my AdapterCode for the ViewHolder.
Thank you for your help in advance!
Here ist my AdapterCode:
class SearchViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RecyclerItemClick itemClickListener;
public TextView wort, praeteritum, partizip2, artikelGrammatik, uebersetzung1, uebersetzung2;
public ImageButton button1, button2;
public SearchViewHolder(#NonNull View itemView) {
super(itemView);
wort = (TextView)itemView.findViewById(R.id.wort);
praeteritum = (TextView)itemView.findViewById(R.id.praeteritum);
partizip2 = (TextView)itemView.findViewById(R.id.partizip2);
artikelGrammatik = (TextView)itemView.findViewById(R.id.artikelGrammatik);
uebersetzung1 = (TextView)itemView.findViewById(R.id.uebersetzung1);
uebersetzung2 = (TextView)itemView.findViewById(R.id.uebersetzung2);
button1 = (ImageButton)itemView.findViewById(R.id.button_id_1);
button2 = (ImageButton) itemView.findViewById(R.id.button_id_2);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemClickListener(RecyclerItemClick ic) {
this.itemClickListener = ic;
}
}
public class SearchAdapter extends RecyclerView.Adapter<SearchViewHolder> {
private Context context;
private List<Lughat> lughats;
public SearchAdapter(Context context, List<Lughat> lughats) {
this.context = context;
this.lughats = lughats;
}
#NonNull
#Override
public SearchViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View itemView = inflater.inflate(R.layout.layout_item, parent, false);
return new SearchViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SearchViewHolder holder, final int position) {
holder.wort.setText(lughats.get(position).getWort());
holder.praeteritum.setText(lughats.get(position).getPraeteritum());
holder.partizip2.setText(lughats.get(position).getPartizip2());
holder.artikelGrammatik.setText(lughats.get(position).getArtikelGrammatik());
holder.uebersetzung1.setText(lughats.get(position).getUebersetzung1());
holder.uebersetzung2.setText(lughats.get(position).getUebersetzung2());
CharSequence praet;
praet = holder.praeteritum.getText();
if (praet.length() == 0) {
holder.praeteritum.setVisibility(View.GONE);
holder.button1.setVisibility(View.GONE);
} else {
holder.praeteritum.setVisibility(View.VISIBLE);
holder.button1.setVisibility(View.VISIBLE);
}
CharSequence part2;
part2 = holder.partizip2.getText();
if (part2.length() == 0) {
holder.partizip2.setVisibility(View.GONE);
} else {
holder.partizip2.setVisibility(View.VISIBLE);
}
CharSequence artGr;
artGr = holder.artikelGrammatik.getText();
if (artGr.length() == 0) {
holder.artikelGrammatik.setVisibility(View.GONE);
holder.button2.setVisibility(View.GONE);
} else {
holder.artikelGrammatik.setVisibility(View.VISIBLE);
holder.button2.setVisibility(View.VISIBLE);
}
CharSequence ueb2;
ueb2 = holder.uebersetzung2.getText();
if (ueb2.length() == 0) {
holder.uebersetzung2.setVisibility(View.GONE);
} else {
holder.uebersetzung2.setVisibility(View.VISIBLE);
}
holder.button1.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.button2.setOnClickListener(new ToastMaker(context.getApplicationContext()));
holder.setItemClickListener(new RecyclerItemClick() {
#Override
public void onItemClickListener(View v, int position) {
Toast.makeText(context, "Begriff", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return lughats.size();
}
}
If I do it also with OnClickListener it does not work too, it does not call the method startSearch.
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence text = materialSearchBar.getText();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
startSearch(text.toString());
}

Loading more data in recyclerview on scroll

I am getting Json data in list which has like 100 of items. I am passing this list to the recyclerview adapter. But i want to pass only 10 items at first. after 10 items when user scrolls the list it should load more data from the list.I have Implemented the scroll listeners and other adapter.I am not sure how to pass 10 items from the json list to adapter.
ScrollListener
public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {
LinearLayoutManager layoutManager;
/**
* Supporting only LinearLayoutManager for now.
*
* #param layoutManager
*/
public PaginationScrollListener(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = layoutManager.getChildCount();
int totalItemCount = layoutManager.getItemCount();
int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
if (!isLoading() && !isLastPage()) {
if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
&& firstVisibleItemPosition >= 0
&& totalItemCount >= getTotalPageCount()) {
loadMoreItems();
}
}
}
protected abstract void loadMoreItems();
public abstract int getTotalPageCount();
public abstract boolean isLastPage();
public abstract boolean isLoading();
}
Adapter
public class PaginationAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<Movie> movies;
private Context context;
private boolean isLoadingAdded = false;
public PaginationAdapter(Context context) {
this.context = context;
movies = new ArrayList<>();
}
public List<Movie> getMovies() {
return movies;
}
public void setMovies(List<Movie> movies) {
this.movies = movies;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.item_list, parent, false);
viewHolder = new MovieVH(v1);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Movie movie = movies.get(position);
switch (getItemViewType(position)) {
case ITEM:
MovieVH movieVH = (MovieVH) holder;
movieVH.textView.setText(movie.getTitle());
break;
case LOADING:
break;
}
}
#Override
public int getItemCount() {
return movies == null ? 0 : movies.size();
}
#Override
public int getItemViewType(int position) {
return (position == movies.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public void add(Movie mc) {
movies.add(mc);
notifyItemInserted(movies.size() - 1);
}
public void addAll(List<Movie> mcList) {
for (Movie mc : mcList) {
add(mc);
}
}
public void remove(Movie city) {
int position = movies.indexOf(city);
if (position > -1) {
movies.remove(position);
notifyItemRemoved(position);
}
}
public void clear() {
isLoadingAdded = false;
while (getItemCount() > 0) {
remove(getItem(0));
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new Movie());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = movies.size() - 1;
Movie item = getItem(position);
if (item != null) {
movies.remove(position);
notifyItemRemoved(position);
}
}
public Movie getItem(int position) {
return movies.get(position);
}
public MovieVH(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.item_text);
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
}
**Getting Api response **
private void callApi() {
apiInterfacePages = ApiClient.getRetrofit().create(APIInterface.class);
Call<CamerasItem> camerasCall = apiInterfacePages.getCameras();
camerasCall.enqueue(new Callback<CamerasItem>() {
#Override
public void onResponse(Call<CamerasItem> call, Response<CamerasItem> response) {
CamerasItem camerasItem = response.body();
itemList = new ArrayList<>();
itemList = camerasItem.getItems();
Log.i("Item", "" + getChannel().getName());
for (int i = 0; i < itemList.size(); i++) {
if (itemList.get(i).getCategory().equals(getChannel().getName())){
if (!itemList.get(i).getUrlMjpeg().endsWith("=mediaRedirect")) {
String videoUrl = itemList.get(i).getUrlMjpeg();
String imageUrl = itemList.get(i).getThumbnail();
String name = itemList.get(i).getName();
String city = itemList.get(i).getCity();
String flag = itemList.get(i).getFlag();
String country= itemList.get(i).getCountry();
modelList.add(new MyModel(videoUrl, imageUrl, name, city, flag,country));
}
}
}
#Override
public void onFailure(Call<CamerasItem> call, Throwable t) {
Log.i("Item", "" + t.getMessage());
}
});
}
So now how to pass to 10 items to recyclerview for the first time and 10 items at each scroll.
You have to set Progressbar inside the activity's xml where Recyclerview is defined.
and loadThumbnail is a function to download thumbnail. it just gives a little delay to scroll down. Now the complete code for the adapter class is as following
public class CamerasAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<MyModel> list;
private Activity mActivity;
private static final int TYPE_VIDEO = 0, TYPE_ADD = 1;
private static final int PAGE_LIMIT = 5;
private int mCurrentLimit = PAGE_LIMIT;
private boolean mIsLoading;
RelativeLayout mLoaderProgress;
public CamerasAdapter(FragmentActivity activity, RelativeLayout loaderLayout) {
mActivity = activity;
mLoaderProgress = loaderLayout;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.li_web_cam_view, viewGroup, false);
return new CamsViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
if (mCurrentLimit == (i + 1) && mCurrentLimit <= list.size() && !mIsLoading) {
mLoaderProgress.setVisibility(View.VISIBLE);
mIsLoading = true;
loadThumbnail(0, i + 1);
} else {
//do nothing
}
((CamsViewHolder) viewHolder).onBindData(mActivity, list.get(i), i);
((CamsViewHolder) viewHolder).emptyView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClickListner.onClick(i, ((CamsViewHolder) viewHolder).tvCamName, list.get(i));
}
});
}
private void loadThumbnail(final int count, int position) {
try {
if (count > 2 || position >= list.size()) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mIsLoading = false;
mCurrentLimit = mCurrentLimit + PAGE_LIMIT;
notifyItemChanged(position - count);
mLoaderProgress.setVisibility(View.GONE);
return;
}
}, 2000);
} else {
if (list.get(position) == null) {
loadThumbnail(count, position + 1);
} else {
Glide.with(mActivity).load(list.get(position).getImage_url()).downloadOnly(new SimpleTarget<File>() {
#Override
public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
loadThumbnail((count + 1), (position + 1));
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
loadThumbnail((count + 1), (position + 1));
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
mLoaderProgress.setVisibility(View.GONE);
mIsLoading = false;
}
}
#Override
public int getItemCount() {
return mCurrentLimit <= list.size() ? mCurrentLimit : list.size();
}
public void setData(List<MyModel> dataList) {
this.list = dataList;
notifyDataSetChanged();
}
ItemClickListner itemClickListner;
public void setListener(ItemClickListner listener) {
itemClickListner = listener;
}
ProgressLoadListener progressLoadListener;
public void setProgressLoadListener(ProgressLoadListener listener) {
progressLoadListener = listener;
}
}
code for xml file
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_above="#+id/loader_progress_bar_layout"
android:background="#f5f5f5"
android:layout_gravity="center" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/loader_progress_bar_layout"
android:visibility="gone"
android:background="#fff"
>
<ProgressBar
android:id="#+id/progress_bar_loader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center" />
</RelativeLayout>
initialize Recyclerview with adapter
public class Main2Activity extends AppCompatActivity {
RecyclerView recyclerView;
RelativeLayout layoutProgressBar;
CamerasAdapter adapter;
List<Item> itemList;
LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
layoutProgressBar = findViewById(R.id.loader_progress_bar_layout);
recyclerView = findViewById(R.id.recycler_view);
adapter = new CamerasAdapter(getActivity(), loaderLayout);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(adapter);
adapter.setProgressLoadListener(new ProgressLoadListener() {
#Override
public void loadProgressBar() {
layoutProgressBar.setVisibility(View.VISIBLE);
}
});
adapter.setData(setAdaperData());
}
public List<MyModel> setAdaperData(){
List<MyModel> modelList = new ArrayList<>();
/*addItemsto list*/
return modelList;
}
}

Android recycleView displaying an emply list

Please i need help on this one. Have been working on it for days but cant figure it out.
I have a recycleView to display a list of names but its displaying empty list, but i can print the list in console.
here,s the code fetching the list
public List<BackendlessUser> userList = new ArrayList<BackendlessUser>();
BackendlessDataQuery query = new BackendlessDataQuery();
Backendless.Data.of( BackendlessUser.class ).find( query, new AsyncCallback<BackendlessCollection<BackendlessUser>>()
{
#Override
public void handleResponse( BackendlessCollection<BackendlessUser> response )
{
userList = response.getCurrentPage();
for( BackendlessUser user : userList ){
Log.d( "USERS : ", user.getEmail() );
}
Log.d("USER LIST", String.valueOf( userList.size() ));
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
and the recyclerView adapter that is supposed to adapt the list to the view ..
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(userList));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<BackendlessUser> mValues;
public SimpleItemRecyclerViewAdapter(List<BackendlessUser> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).getProperty("idno").toString());
holder.mContentView.setText(mValues.get(position).getProperty("fname").toString());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getProperty("idno").toString());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getProperty("idno").toString());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public BackendlessUser mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}

java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item

I want to display a list in fragment. i am using a custom arraylist. it is giving me classcast exception. i searched for the soluo solvetion but it dosnt solve my problem. i am new to android so i have no idea how this.. can anyone help..
this is my Item class
public class Item {
public String item_name;
public String item_desc;
public String item_qty;
public Item(String item_name, String item_desc,String item_qty) {
super();
this.item_name = item_name;
this.item_desc = item_desc;
this.item_qty = item_qty;
}
public String getItem_name(){
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name=item_name;
}
public String getItem_desc()
{
return item_desc;
}
public void setItem_desc(String item_desc)
{
this.item_desc=item_desc;
}
public String getItem_qty()
{
return item_qty;
}
public void setItem_qty(String item_qty) {
this.item_qty = item_qty;
}
}
this is my addstock fragment
public class AddStock extends Fragment {
EditText edit_item_name,edit_item_desc,edit_item_qty;
Button btn_save;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_stock, container, false);
edit_item_name = (EditText)rootView.findViewById(R.id.edittext_item_name);
edit_item_desc = (EditText) rootView.findViewById(R.id.editText_item_desc);
edit_item_qty = (EditText) rootView.findViewById(R.id.editText_item_qty);
btn_save = (Button) rootView.findViewById(R.id.button_Save);
MainActivity act=(MainActivity)this.getActivity();
final ArrayList stock = act.arrayList;
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item_name=edit_item_name.getText().toString();
String item_desc=edit_item_desc.getText().toString();
String item_qty=edit_item_qty.getText().toString();
stock.add(item_name);
stock.add(item_desc);
stock.add(item_qty);
Toast.makeText(AddStock.this.getActivity(), "Saved", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
this is my viewstock fragment
public class ViewStock extends Fragment {
public ViewStock() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_view_stock, container, false);
ListView listview = (ListView)rootview.findViewById(R.id.list);
// Context mCtx = getActivity().getApplicationContext();
MainActivity act=(MainActivity)this.getActivity();
ItemAdapter adapter = new ItemAdapter(getActivity(),R.layout.list_item,act.arrayList);
listview.setAdapter(adapter);
return rootview;
}
}
this is my main activity
Public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FrameLayout mContentFrame;
FragmentManager fragmentManager;
private static final String PREFERENCES_FILE = "mymaterialapp_settings";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
public ArrayList<Item> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
setUpToolbar();
arrayList=new ArrayList<Item>();
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
setUpNavDrawer();
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mContentFrame = (FrameLayout) findViewById(R.id.nav_contentframe);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment newFragment;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
newFragment = new AddStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 0;
mDrawerLayout.closeDrawers();
return true;
case R.id.navigation_item_2:
newFragment = new ViewStock();
transaction.replace(R.id.nav_contentframe, newFragment);
transaction.addToBackStack(null);
transaction.commit();
mCurrentSelectedPosition = 1;
return true;
default:
return true;
}
}
});
//fragmentManager.beginTransaction().replace(R.id.nav_contentframe, fragment).commit();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
Menu menu = mNavigationView.getMenu();
menu.getItem(mCurrentSelectedPosition).setChecked(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
private void setUpToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
}
private void setUpNavDrawer() {
if (mToolbar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
if (!mUserLearnedDrawer) {
mDrawerLayout.openDrawer(GravityCompat.START);
mUserLearnedDrawer = true;
saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
}
}
public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(settingName, settingValue);
editor.apply();
}
public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
return sharedPref.getString(settingName, defaultValue);
}
}
this is my ItemAdapter
public class ItemAdapter extends ArrayAdapter<Item> {
Context context;
public ItemAdapter(Context context, int resourceId,
ArrayList<Item> items) {
super(context, resourceId, items);
this.context = context;
}
/* public int getCount() {
return items.size();
}
public Item getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
*/
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
Item rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.txtItemName = (TextView) convertView.findViewById(R.id.txt_item_name);
holder.txtItemDesc = (TextView) convertView.findViewById(R.id.txt_item_desc);
holder.txtItemQty = (TextView) convertView.findViewById(R.id.txt_item_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtItemName.setText(rowItem.getItem_name());
holder.txtItemDesc.setText(rowItem.getItem_desc());
holder.txtItemQty.setText(rowItem.getItem_qty());
return convertView;
}
private class ViewHolder {
TextView txtItemName;
TextView txtItemDesc;
TextView txtItemQty;
}
}
this is the exception m getting
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.owner.stock.Item
at com.example.owner.stock.ItemAdapter.getView(ItemAdapter.java:60)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1673)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
07-22 23:34:00.334 20992-20992/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
You are adding String objects to a list that is typed to take Item objects.
Instead of:
stock.add(someString);
stock.add(someString);
stock.add(someString);
Do
stock.add(new Item(someString, someString, someString));