Duplicate items in the recyclerView - android

I am new here, I have an activity that contains ViewPager with two Fragments. Each Fragment has a RecyclerView. on selecting a tab through OnTabSelection items in the RecyclerView gets repeated. I can't understand what is causing this problem.
I am using DataHandler to save the data because I have to use this data in other activities as well.
class DataHandler {
private ArrayList<MenuHolder> listOfItemsFromJson;
private static DataHandler mInstance = null;
static public DataHandler getInstance() {
if (null == mInstance) {
mInstance = new DataHandler();
}
return mInstance;
}
public DataHandler() {
listOfItemsFromJson = new ArrayList<>();
}
public ArrayList<MenuHolder> getListOfItemsFromJson() {
return listOfItemsFromJson;
}
public void clearList() {
listOfItemsFromJson.clear();
}
public void addData(MenuHolder holder) {
listOfItemsFromJson.add(holder);
}
public MenuHolder getData(int position) {
return listOfItemsFromJson.get(position);
}
public void removeData(int position) {
listOfItemsFromJson.remove(getData(position));
}
public int size() {
return listOfItemsFromJson.size();
}
}
Here is my Fragment
class ComboRecycler extends Fragment {
private ArrayList<Integer> index = new ArrayList<>();
private LinearLayout mViewCartLayout;
private RelativeLayout relativeLayout;
private RecyclerView recyclerView;
RecyclerView.Adapter recyclerAdapter;
RecyclerView.LayoutManager recylerViewLayoutManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_combo, container, false);
relativeLayout = (RelativeLayout) view.findViewById(R.id.relativelayout1);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recylerViewLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recylerViewLayoutManager);
new FetchTask().execute();
return view;
}
public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
#Override
protected JSONArray doInBackground(Void... params) {
JSONArray jsonArray;
........
}
#Override
protected void onPostExecute(JSONArray result) {
if (result != null) {
try {
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getData(i).isCombo()) {
DataHandler.getInstance().removeData(i);
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject mJsonObject = result
.getJSONObject(i);
MenuHolder mDataHolder = new MenuHolder();
......
mDataHolder.setCombo(true);
mDataHolder.setItemCount("0");
DataHandler.getInstance().addData(mDataHolder);
}
setAdapter();
} catch (Exception e) {
}
}
}
}
private void setAdapter() {
index.clear();
for (int i = 0; i < DataHandler.getInstance().size(); i++) {
if (DataHandler.getInstance().getListOfItemsFromJson().get(i).isCombo()) {
index.add(i);
}
}
recyclerComboAdapter = new RecyclerComboAdapter(getActivity(), index);
recyclerView.setAdapter(recyclerComboAdapter);
}
}
Here is my RecyclerAdapter
class RecyclerComboAdapter extends RecyclerView.Adapter<RecyclerComboAdapter.ViewHolder> {
Context context;
View view1;
ViewHolder viewHolder1;
ArrayList<Integer> index;
LinearLayout mViewCart;
Recycler recycler;
private AQuery mQuery;
public RecyclerComboAdapter(Context context1, ArrayList<Integer> index) {
this.index = index;
context = context1;
mQuery = new AQuery(context1);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view1 = LayoutInflater.from(context).inflate(R.layout.combo_meals_adapter, parent, false);
viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final int pos = position;
MenuHolder menuHolder =DataHandler.getInstance().getData(index.get(position));
holder.itemName.setText(menuHolder.getItemname());
holder.itemPrice.setText(menuHolder.getItemprice());
mQuery.id(holder.imageView).image(menuHolder.getItemPicture());
holder.counter.setText(menuHolder.getItemCount());
}
#Override
public int getItemCount() {
return index.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView add, minus, plus, counter, itemName, itemPrice;
ViewHolder(View v) {
super(v);
itemName = (TextView) v.findViewById(R.id.itemnametxt);
imageView = (ImageView) v.findViewById(R.id.image);
itemPrice = (TextView) v.findViewById(R.id.price);
minus = (TextView) v.findViewById(R.id.minus);
plus = (TextView) v.findViewById(R.id.plus);
counter = (TextView) v.findViewById(R.id.count);
add = (TextView) v.findViewById(R.id.addtxt);
}
}
}
After swiping the list multiple times I am seeing repeated list items. Please help me with this problem. Thanks in advance.

Related

I am not able to call recyclerview adapter's functions

I have a recyclerView adapter named as CustomAdapter in the MainActivity, I am getting the data by parsing the JSON and this data is used to set the textview inCustomAdapter class.
When I start my application,I am not showing the recyclerView list and the adapter is not being called. So my problem is I am not able to call the customAdapter's functions like onBindViewHolder,onCreateViewHolder.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
Context context;
RealmResults<Film> realmResults;
View.OnTouchListener listener;
Realm realm;
public CustomAdapter(Context context, View.OnTouchListener listener) {
this.context = context;
this.listener = listener;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_liste, parent, false);
MyViewHolder viewHolder = new MyViewHolder(root);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
Realm.init(context);
RealmResults<Film> films = realm.where(Film.class).findAll();
Film f = films.get(position);
for(film film:filmler) {
try {
holder.title.setText(film.getTitle());
holder.year.setText(film.getYear());
holder.poster.setImageURI(film.getPoster());
if (film.getPoster().toString().equals("N/A") == true) {
Picasso.get().load(R.drawable.noImage).fit().into(holder.image);
} else {
Picasso.get().load(film.getPoster()).into(holder.image);
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
if(realmResults==null)
{
return 0;
}
return realmResults.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnTouchListener {
public TextView title, year;
public ImageView image;
public LinearLayout linearLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title_id);
year = itemView.findViewById(R.id.year_id);
image = itemView.findViewById(R.id.image_id);
linearLayout = itemView.findViewById(R.id.linearlayout_id);
linearLayout.setOnTouchListener(listener);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_SCROLL){
return true;
}
return false;
}
}
}
My MainActivity Class:
final StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
JSONObject jsonObject1 = new JSONObject(response);
String response = jsonObject1.getString("Response");
if (response.equals("True") && jsonObject1.has("Search")==true) {
JSONArray array1 = jsonObject1.getJSONArray("Search");
for (int i = 0; i < array1.length(); i++) {
final JSONObject films = array1.getJSONObject(i);
realm1.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm1) {
Film film = realm1.createObject(Film.class);
try {
film.setTitle(filmler.getString("Title"));
film.setYear(filmler.getString("Year"));
film.setPoster(filmler.getString("Poster"));
realm1.copyToRealm(film);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
for (int j = 0; j < array1.length(); j++) {
array1.remove(j);
}
adapter = new CustomAdapter(this, this);
recycle1.setAdapter(adapter);
you are going wrong in onBindViewHolder.
Try to pass list in constructor
public CustomAdapter(Context context, View.OnTouchListener
listener,RealmResults<film> realmResults) {
this.context = context;
this.listener = listener;
this.realmResults = realmResults;
}
and Remove this code from bindViewHolder
Log.d(TAG, "onBindViewHolder : called.");
Realm.init(context);
//film filmler = filmList.get(position);
//realm = Realm.getDefaultInstance();
RealmResults<film> filmler =
realm.where(film.class).findAll();
film f = filmler.get(position);
don't call for loop there in onBindViewHolder for set data just do following
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int
position) {
film item = realmResults.get(position);
if(item!=null && item.isValid()){
holder.baslik.setText(item.getTitle());
holder.yil.setText(item.getYear());
holder.resim.setImageURI(item.getPoster());
if (item.getPoster().toString().equals("N/A")) {
Picasso.get().load(R.drawable.resimyok).fit().into(holder.resim);
} else {
Picasso.get().load(film.getPoster()).into(holder.resim);
}
}
}
Fix this below for getting response and save it to realm
JSONArray array1 = jsonObject1.getJSONArray("Search");
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.createOrUpdateAllFromJson(filn.class, array1);
realm.commitTransaction();
//get all saved data from realm
RealmResults<T> results =
realm.where(film.class).query.findAll();
adapter = new
CustomAdapter(getApplicationContext(),MainActivity.this,results);
recycle1.setAdapter(adapter);
arama.getText().clear();

Horizontal and vertical recyclerview parsing json data in Android

See sanpshot here
jObject = new JSONObject(result);
JSONObject resultObj = jObject.getJSONObject("result");
for(int i = 0; i < firstproducts.size(); i++) {
try {
title = firstproducts.get(i).getString("category");
categoryIcon = firstproducts.get(i).getString("icon_img");
Log.e("For I","Value : "+title);
for(int j = 0; j < secondproducts.size(); j++) {
if(title.equalsIgnoreCase(secondproducts.get(j).getString("category"))){
categoryIcon = secondproducts.get(j).getJSONObject("info").getString("img");
JSONArray products=null;
products = firstproducts.get(j).gptJSONArray("Products"); if(products!=null) {
for (int k = 0; k < products.length(); k++) {
JSONObject jsonObj = products.getJSONObject(k);
content = jsonObj.getString("description");
points = jsonObj.getString("points");
imageUrl = jsonObj.getString("image");
secondarraylist.add(new ChildModel(content,points,rating,imageUrl));
}
}
mainarraylist.add(new MainModel(title,categoryIcon,secondarraylist));
finally i set this above main arraylist to recyclerview adapter
------------------------------- ---------
Mian Model class as below -child model inside 3 string values will be there.
public class MainModel {
String title;
String categoryIcon;
private List<ChildModel> ChildItems;
public MainModel() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategoryIcon() {
return categoryIcon;
}
public void setCategoryIcon(String categoryIcon) {
this.categoryIcon = categoryIcon;
}
public List<ChildModel> getChildItems() {
return ChildItems;
}
public void setItems(List<ChildModel> ChildItems) {
this.ChildItems = ChildItems;
}
}
---------------------------------------
Main adapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ProductViewHolder> {
private final Context mContext;
List<MainModel> maindata;
public MainAdapter(Context mContext, List<MainModel> ProductList) {
this.mContext = mContext;
this.maindata=ProductList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.product_list_store, parent, false);
return new ProductViewHolder(view);
}
public class ProductViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public final ImageView categoryIcon;
public final ImageView leftArrow;
public final ImageView rightArrow;
public final View categoryDiver;
private ChildAdapter horizontalAdapter;
private RecyclerView horizontalList;
private LinearLayoutManager llm;
public ProductViewHolder(View view) {
super(view);
Context context = itemView.getContext();
title = (TextView) view.findViewById(R.id.product_textForHeader);
categoryIcon = (ImageView) view.findViewById(R.id.product_Iconimageview);
leftArrow = (ImageView)view.findViewById(R.id.product_leftside_arrow);
rightArrow = (ImageView)view.findViewById(R.id.product_rightside_arrow);
categoryDiver = view.findViewById(R.id.product_Divider_view);
horizontalList = (RecyclerView) itemView.findViewById(R.id.horizontal_layout);
llm = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
horizontalList.setLayoutManager(llm);
horizontalAdapter = new ChildAdapter(context);
horizontalList.setAdapter(horizontalAdapter);
}
}
#Override
public void onBindViewHolder(final ProductViewHolder holder, int position) {
holder.title.setText(maindata.get(position).getTitle());
holder.horizontalAdapter.setData(maindata.get(position).getStoreItems()); // List of Strings
holder.horizontalAdapter.setRowIndex(position);
holder.leftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("left");
if (holder.llm.findFirstCompletelyVisibleItemPosition() > 0){
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() - 1);
}
}
});
holder.rightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("right");
holder.horizontalList.smoothScrollToPosition(holder.llm.findFirstVisibleItemPosition() + 1);
}
});
if(position == maindata.size()-1)
holder.categoryDiver.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
//return 0;
return maindata.size();
}
}
-------------------------------------------
ChildAdapter
public class ChildAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
private List<ChildModel> childdata;
private ImageLoader imageLoader;
private int mRowIndex = -1;
public ChildAdapter(Context context) {
this.context = context;
}
public void setData(List<ChildModel> data) {
if (childdata != data) {
childdata = data;
notifyDataSetChanged();
}
}
publindex;
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
public final TextView content;
public final TextView rating;
public final TextView points;
public final NetworkImageView img_item;
public final ImageView img_rating;
public ItemViewHolder(View view) {
super(view);
content = (TextView) view.findViewById(R.id.category_item_title);
rating = (TextView) view.findViewById(R.id.text_rating);
points = (TextView) view.findViewById(R.id.category_points);
img_item = (NetworkImageView) view.findViewById(R.id.category_item_imageView);
img_rating= (ImageView) view.findViewById(R.id.img_rating);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
View itemView = LayoutInflater.from(context).inflate(R.layout.store_category_item, parent, false);
ItemViewHolder holder = new ItemViewHolder(itemView);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder viewholder, int position) {
ItemViewHolder holder=(ItemViewHolder)viewholder;
holder.content.setText(childdata.get(position).getContent());
holder.points.setText(childdata.get(position).getPoints());
holder.rating.setText(childdata.get(position).getRating());
holder.itemView.setTag(position);
}
#Override
public int getItemCount() {
return childdata.size();
}
}
I am doing a project with horizontal and vertical recyclerview same like a play store. I have done all the designs like 2 adapters and 2 model class.
The problem is I parsed json and set all the data to 2 array list so all the data come to horizontal adapters. how to set horizontal values from arraylist according to below heading thats dynamic.
This is my API: bikes, cars, trucks; I need to set this data vertical recyclerview heading and inside products array that is horizontal recyclerview:
I can tell you the approach-->Get all child json in the main array-->then in each of these json object get the products jsonobject and set them accordingly

Sticky Header RecyclerView with multiple ArrayLists

I am implementing sticky header with RecyclerView. I have three sections (i.e 3 sticky headers) and they are working fine.Now I have taken three arraylists inside each section, I have initialized these list in my adapter and I am trying to get data of these lists on basis of header id inside onBindViewHolder. But it is not giving me the full list,just one string from each list (i.e under first section--data on first position of mylist,,,under second section-- data on second position of mylist1 ---under third section-- data on third position of mylist2)
Please Help !!
Code in Context:
StickyTestAdapter
public class StickyTestAdapter extends RecyclerView.Adapter<StickyTestAdapter.ViewHolder> implements
StickyHeaderAdapter<StickyTestAdapter.HeaderHolder> {
private Context mContext;
private ArrayList<String> mylist;
private ArrayList<String> mylist1;
private ArrayList<String> mylist2;
private static int countposition;
private String HEADER_FIRIST="HEADER_FIRIST";
private String HEADER_SECOND="HEADER_SECOND";
private String HEADER_THIRD="HEADER_THIRD";
public StickyTestAdapter(Context context) {
prepareData();
prepareData1();
prepareData2();
this.mContext=context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.item_test, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
long rowType= getHeaderId(position);
Log.e("getHeaderId----",""+rowType);
if (rowType==0){
if(!mylist.equals(""))
{
Log.e("list_data----", "" + mylist.get(position));
viewHolder.item.setText(mylist.get(position));
}
else
{
Log.e("Error--0--", "" + "error");
}
} else if (rowType==1){
if(!mylist1.equals(""))
{
Log.e("list_data1----", "" + mylist1.get(position));
viewHolder.item.setText(mylist1.get(position));
}
else
{
Log.e("Error---1-", "" + "error");
}
} else if (rowType==2){
if(!mylist2.equals(""))
{
Log.e("list_data2----", "" + mylist2.get(position));
viewHolder.item.setText(mylist2.get(position));
}
else
{
Log.e("Error----2", "" + "error");
}
}
}
#Override
public int getItemCount() {
if (getHeaderId(countposition)==0){
Log.e("mylist",""+mylist.size());
return mylist.size();
}else if (getHeaderId(countposition)==1){
Log.e("mylist1",""+mylist1.size());
return mylist1.size();
}else if (getHeaderId(countposition)==2){
Log.e("mylist2",""+mylist2.size());
return mylist2.size();
}
return 0;
}
#Override
public long getHeaderId(int pos) {
return pos;
}
#Override
public HeaderHolder onCreateHeaderViewHolder(ViewGroup parent) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.header_test, parent, false);
return new HeaderHolder(view);
}
#Override
public void onBindHeaderViewHolder(HeaderHolder viewholder, int count) {
countposition=count;
if (getItemViewType(count)==0){
viewholder.headertext.setText(HEADER_FIRIST);
}else if (getItemViewType(count)==1){
viewholder.headertext.setText(HEADER_SECOND);
}else if (getItemViewType(count)==2){
viewholder.headertext.setText(HEADER_THIRD);
}
}
static class ViewHolder extends RecyclerView.ViewHolder {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
item = (TextView)itemView.findViewById(R.id.text_item);
}
}
static class HeaderHolder extends RecyclerView.ViewHolder {
public TextView headertext;
public HeaderHolder(View itemView) {
super(itemView);
headertext = (TextView)itemView.findViewById(R.id.header_text);
}
}
#Override
public int getItemViewType(int position) {
return position;
}
public void prepareData()
{
mylist=new ArrayList<>();
mylist.add("rajendra");
mylist.add("rani");
mylist.add("rahul");
}
public void prepareData1()
{
mylist1=new ArrayList<>();
mylist1.add("ravi");
mylist1.add("vikram");
mylist1.add("rakesh");
}
public void prepareData2()
{
mylist2=new ArrayList<>();
mylist2.add("apple");
mylist2.add("ashok");
mylist2.add("vikash");
}
}
Question is quite old. But that code looks complicated to read, personally I try to not reinvent what others did quite well by creating libraries.
GitHub is full of source that you can import. Some examples: FlexibleAdapter, FastAdapter, Epoxy and others.
I have build the first one, but you can try the others as well.
With mine, having multiple views and headers with sections is quite easy, I point here the wiki page where I define the section and how to initialize it.
Along with this feature, you have a lot more functionalities that makes your life easier.
I divide arraylist into 3 section based on alphabet like contactlist.
For that i use SectionedRecyclerViewAdapter
MainActivity.java
public class MainActivity extends AppCompactActivity {
private SectionedRecyclerViewAdapter sectionAdapter;
#Override
public View onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
sectionAdapter = new SectionedRecyclerViewAdapter();
for(char alphabet = 'a'; alphabet <= 'z';alphabet++) {
List<String> contacts = getContactsWithLetter(alphabet);
if (contacts.size() > 0) {
sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
}
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
return view;
}
#Override
public void onResume() {
super.onResume();
if (getActivity() instanceof AppCompatActivity) {
AppCompatActivity activity = ((AppCompatActivity) getActivity());
if (activity.getSupportActionBar() != null)
activity.getSupportActionBar().setTitle(R.string.nav_example1);
}
}
private List<String> getContactsWithLetter(char letter) {
List<String> contacts = new ArrayList<>();
for (String contact : getResources().getStringArray(R.array.names_)) {
if (contact.charAt(0) == letter) {
contacts.add(contact);
}
}
return contacts;
}
private class ContactsSection extends StatelessSection {
String title;
List<String> list;
ContactsSection(String title, List<String> list) {
super(new SectionParameters.Builder(R.layout.section_ex1_item)
.headerResourceId(R.layout.section_ex1_header)
.build());
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size();
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return new ItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
String name = list.get(position);
itemHolder.tvItem.setText(name);
itemHolder.imgItem.setImageResource(name.hashCode() % 2 == 0 ? R.drawable.ic_face_black_48dp : R.drawable.ic_tag_faces_black_48dp);
itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), String.format("Clicked on position #%s of Section %s", sectionAdapter.getPositionInSection(itemHolder.getAdapterPosition()), title), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
}
}
private class HeaderViewHolder extends RecyclerView.ViewHolder {
private final TextView tvTitle;
HeaderViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
}
}
private class ItemViewHolder extends RecyclerView.ViewHolder {
private final View rootView;
private final ImageView imgItem;
private final TextView tvItem;
ItemViewHolder(View view) {
super(view);
rootView = view;
imgItem = (ImageView) view.findViewById(R.id.imgItem);
tvItem = (TextView) view.findViewById(R.id.tvItem);
}
}
}
use structure similar to
public class MultiArray<T> {
List<ItemGroup> lists = new ArrayList<>();
public void addList(String headerText, List<T> list) {
lists.add(new ItemGroup(headerText, list));
}
public int itemCount() {
int count = 0;
for (ItemGroup group : lists) {
count += group.count();
}
return count;
}
public T getItem(int position) {
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.item(position - count);
}
count += group.count();
}
return null;
}
public int getGroupIndex(int position) {
int count = 0;
int groupIndex = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return groupIndex;
}
count += group.count();
groupIndex++;
}
return -1;
}
public String getHeaderText(int position){
int count = 0;
for (ItemGroup group : lists) {
if (count + group.count() >= position) {
return group.headerText;
}
count += group.count();
}
return "";
}
class ItemGroup {
public final String headerText;
public final List<T> list;
public ItemGroup(String headerText, List<T> list) {
this.headerText = headerText;
this.list = list;
}
public int count() {
return list.size();
}
public T item(int position) {
return list.get(position);
}
}
}
you can optimize it for faster performance

Remove an item in RecyclerView- Android

I am facing a problem, I could not remove an Item in RecyclerView.
I am trying to search in Internet, but could not see any solution
I am following to this post
Android RecyclerView addition & removal of items
But I still could not remove the item selected
Below is my code for my adapter and fragement
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
List<VideoDetails> contents2;
Context mContext;
ImageLoader imageLoader;
static final int TYPE_HEADER = 0;
static final int TYPE_CELL = 1;
public RecyclerViewAdapter(List<VideoDetails> contents) {
this.contents2 = contents;
}
public RecyclerViewAdapter(Context context, List<VideoDetails> contents) {
mContext = context;
this.contents2 = contents;
imageLoader = new ImageLoader(context);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return contents2.size();
}
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
View view = null;
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_card_small2, parent, false);
ViewHolder vh = new ViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder,final int position) {
holder.title.setText(contents2.get(position).getTitle());
holder.image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Log.d("thien.van","on Click onBindViewHolder");
contents2.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, contents2.size());
}
});
}
public Bitmap getThumbnail(String str) {
Bitmap bMap = ThumbnailUtils.createVideoThumbnail(str, MediaStore.Video.Thumbnails.MINI_KIND);
return bMap;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public ImageView image;
public ProgressBar progressBar;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
image = (ImageView) itemView.findViewById(R.id.thumbnail);
progressBar = (ProgressBar) itemView.findViewById(R.id.progress);
// image.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Log.d("thien.van","onClick getAdapterPosition () = "+getAdapterPosition());
removeAt(getAdapterPosition());
}
}
public void removeAt(int position) {
contents2.remove(position);
notifyDataSetChanged();
}
}
RecyclerViewFragment
public class RecyclerViewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private static final int ITEM_COUNT = 2;
private List<Object> mContentItems = new ArrayList<>();
private static List<VideoDetails> mContentItems2 = new ArrayList<>();
public static RecyclerViewFragment newInstance() {
return new RecyclerViewFragment();
}
public static RecyclerViewFragment newInstance(List<VideoDetails> contentItems) {
RecyclerViewFragment myFragment = new RecyclerViewFragment();
// mContentItems = contentItems;
Bundle args = new Bundle();
args.putSerializable("thienvan", (Serializable) contentItems);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mContentItems2 = (List<VideoDetails>) getArguments().getSerializable("thienvan");
// Log.d("thien.van","Fragment file name = "+mContentItems2.get(0).getTitle());
return inflater.inflate(R.layout.fragment_recyclerview, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(layoutManager);
//mRecyclerView.setHasFixedSize(true);
mAdapter = new RecyclerViewMaterialAdapter(new RecyclerViewAdapter(getActivity().getBaseContext(),mContentItems2));
mRecyclerView.setAdapter(mAdapter);
/*{
for (int i = 0; i < ITEM_COUNT; ++i)
mContentItems.add(new Object());
mAdapter.notifyDataSetChanged();
}*/
MaterialViewPagerHelper.registerRecyclerView(getActivity(), mRecyclerView, null);
}
//http://android--code.blogspot.com/2015/12/android-recyclerview-add-remove-item.html
}
I could not remove an item inside Adapter class.
Anybody could help me ?
To get the correct position for remove you should call holder.getAdapterPosition() and use this value for all remove and notify operations. Android studio shows a warning for this, so make sure to check the warnings first. And why for getItemCount you return 2?
public void onClick(View view) {
int newPosition = holder.getAdapterPosition();
Log.d("thien.van","on Click onBindViewHolder");
contents2.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, contents2.size());
}
Remove single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
Remove multiple items
Remove "Camel" and "Sheep" from the list.
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
Remove all items
Clear the whole list.
data.clear();
adapter.notifyDataSetChanged();

Android Issue with RecyclerView: view get override

I am using RecyclerView for first tab and ListView for other tabs.
when I scroll in RecyclerView it of same for ListView. but when I swipe from first tab to other tab and return to first tab I get the result as below
For the first time:
After travelling from other tab:
public class QuestionListAdapter extends RecyclerView.Adapter<QuestionListAdapter.CustomViewHolder> {
private List<QuestionListModel> feedItemList;
private Context mContext;
private String UserIDFromDatabase = "";
private ConnectionDetector connectionDetector;
public QuestionListAdapter(Context context, List<QuestionListModel> feedItemList, String UserIDFromDatabase) {
this.feedItemList = feedItemList;
this.mContext = context;
this.UserIDFromDatabase = UserIDFromDatabase;
connectionDetector = new ConnectionDetector(mContext);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.buds_profile_list_child, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
QuestionListModel feedItem = feedItemList.get(i);
// Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getQuestion()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.textView = (TextView) view.findViewById(R.id.textView_ask_question_bplc);
}
}
}
Fragment:
public class QuestionFragment extends Fragment {
ConnectionDetector connectionDetector;
View rootView;
String UserIDFromDatabase = "";
int sendToServerOffsetPub = 0;
Boolean callSuccessful = false;
private RecyclerView mRecyclerView;
private QuestionListAdapter adapter;
private com.oi.example.swipyrefreshlayout.SwipyRefreshLayout swipeRefreshLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.public__question_fragment, container, false);
initializeScreen();
return rootView;
}
private void initializeScreen() {
Utility.sp = getActivity().getSharedPreferences("User_Details", Context.MODE_PRIVATE);
UserIDFromDatabase = Utility.sp.getString("UserID", "");
// Initialize recycler view
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_public__question_paqf);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new QuestionListAdapter(getActivity(), Utility.arrayListQuestionListModels, UserIDFromDatabase);
mRecyclerView.setAdapter(adapter);
connectionDetector = new ConnectionDetector(getActivity());
swipeRefreshLayout = (com.oi.example.swipyrefreshlayout.SwipyRefreshLayout) rootView.findViewById(R.id.swipe_refresh_public_listview_paqf);
swipeRefreshLayout.setColorSchemeResources(R.color.color_dark_grey);
swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if (direction == SwipyRefreshLayoutDirection.BOTTOM) {
if (connectionDetector.isConnectingToInternet()) { // if 1
if ((Utility.publicCount > 0) && (Utility.arrayListQuestionListModels.size() > 0)) {
sendToServerOffsetPub++;
try {
callSuccessful = new getQuestionListOnProfile(getActivity(), Utility.referenceForProfileID, sendToServerOffsetPub, "PUBLIC").execute().get();
} catch (InterruptedException | ExecutionException e) {
callSuccessful = false;
}
if (!callSuccessful) {
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
} else {
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Utility.ID = (Utility.arrayListQuestionListModels.get(position).getId());
RateFeedController rateFeedController = new RateFeedController(getActivity());
ArrayList<HashMap<String, String>> DetailsArraylist = new ArrayList<HashMap<String, String>>();
DetailsArraylist = rateFeedController.getDetailsForSays(Utility.ID);
if (DetailsArraylist.size() > 0) {
String creatorID = DetailsArraylist.get(0).get("userID");
if (creatorID.equalsIgnoreCase(BudsProfileActivity.UserIDFromDatabase)) {
Utility.attachedListPPFM = 2;
}
Intent intentSays = new Intent(getActivity(), SaysScreenActivity.class);
intentSays.putExtra("ProfileBACKFLAG", "BudsProfileActivity");
startActivity(intentSays);
} else {
if (connectionDetector.isConnectingToInternet()) {// If 2
new GetFromServer(getActivity(), Integer.toString(Utility.ID), BudsProfileActivity.UserIDFromDatabase).execute();
} else {
Toast.makeText(getActivity(), Constants.INTERNET_CONNECTION, Toast.LENGTH_SHORT).show();
}// End of If 2
}
}
}));
}
}
Don't know what was wrong, but I just remove the parent Layout SwipyRefreshLayout and the My issue get solved..

Categories

Resources