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();
Related
I just want to create a list that will show currently selected item text when I click "Selanjutnya" button, but I don't know how to do that.
So when I click "Selanjutnya", it will show 22, 23. Currently, I use Big Nerd Ranch multi-select to make multi-selection work.
implementation 'com.bignerdranch.android:recyclerview-multiselect:+'
And here is my Codes.
Adapter
public class KetuaAbsenAdapter extends RecyclerView.Adapter<KetuaAbsenAdapter.ViewHolder> {
private List<KetuaAbsenList> listItems;
private Context context;
private MultiSelector mMultiSelector = new MultiSelector();
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
return new ViewHolder(v);
}
public KetuaAbsenAdapter(List<KetuaAbsenList> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final KetuaAbsenList listItem = listItems.get(position);
holder.textViewMuridno.setText(listItem.getMuridno());
holder.textViewMuridnama.setText(listItem.getMuridnama());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends SwappingHolder implements View.OnClickListener {
public TextView textViewMuridno;
public TextView textViewMuridnama;
public TextView textViewMuridkelas;
public LinearLayout list_item_linear;
public ViewHolder(View itemView) {
super(itemView, mMultiSelector);
textViewMuridno = (TextView) itemView.findViewById(R.id.muridno);
textViewMuridnama = (TextView) itemView.findViewById(R.id.muridnama);
textViewMuridkelas = (TextView) itemView.findViewById(R.id.muridkelas);
list_item_linear = (LinearLayout) itemView.findViewById(R.id.list_item_linear);
list_item_linear.setOnClickListener(this);
itemView.setOnClickListener(this);
mMultiSelector.setSelectable(true);
}
#Override
public void onClick(View v) {
if (mMultiSelector.tapSelection(this)) {
Toast.makeText(context, "terpilih", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "tidak terpilih", Toast.LENGTH_LONG).show();
}
}
}
}
List Class
public class KetuaDaftarAbsen extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<KetuaAbsenList> listItems;
EditText YangTidakHadir;
Button KetuaLanjut;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ketua_daftar_absen);
YangTidakHadir = (EditText)findViewById(R.id.YangTidakHadir);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));
}
public void loadRecyclerViewData(){
final String url = "https://gameblong.com/raset/daftar_absen.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
String status = jsonObject.getString("status");
if(status.equals("sukses")){
JSONArray array = jsonObject.getJSONArray("semua");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
KetuaAbsenList item = new KetuaAbsenList(
o.getString("murid_no"),
o.getString("murid_nama"),
o.getString("murid_kelas")
);
listItems.add(item);
}
} else {
}
adapter = new KetuaAbsenAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String muno = intent.getStringExtra("muridnomor");
KetuaLanjut = (Button)findViewById(R.id.KetuaLanjut);
KetuaLanjut.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, muno, Toast.LENGTH_LONG).show();
}
});
}
};
}
I can use mMultiSelector.getSelectedPositions(); on my Adapter, but only this only gives current selected position (like 0, 1),
You can create an Interface that you add to your adapter and a listener for it.
public interface OnAdapterItemClicked {
// you can name it what ever you need add pass more parameters
void itemClicked(String text);
}
then in your adapter, you initialise it and add the listener on the click event,
private OnAdapterItemClicked mListener = null;
...
#Override
public void onBindViewHolder(#NonNull YourAdapter.ViewHolder holder,
int position) {
...
holder.YourBtn.setOnClickListener(....{
mListener.itemClicked("string you need to pass")
});
...
}
...
public void setOnItemClickListener(OnAdapterItemClicked listener) {
this.mListener = listener;
}
finally in you activity/fragment you add a listener on the recyclerview
rv.setOnItemClickListener(new OnAdapterItemClicked () {
#Override
public void itemClicked(String text) {
Log.d(TAG, "itemClicked: "+text);
}
});
In your adapter, you can add onClickListener like this
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your logic goes here
}
});
return new ViewHolder(v);
}
I have a list made with RecyclerView. I can add the ad to the bottom, but I get an error when I want to add it to the middle.
For example, I can't add the ad to line 2. I get error again when I increase getItemCount value by 1 (return movies.size() + 1). What I haven't tried.
My Adapter
public class SeriesActivityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Movies> movies;
private static final int ITEM = 0;
private static final int BANNER = 1;
TinyDB tinyDB;
private Activity context;
public SeriesActivityAdapter(Activity c, List<Movies> movies) {
this.movies= movies;
this.context = c;
tinyDB = new TinyDB(c);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType==BANNER && !tinyDB.getBoolean("remove_ads")){
View view = LayoutInflater.from(context).inflate(R.layout.item_ad, parent,false);
return new MyViewBanner(view);
}
else{
View view = LayoutInflater.from(context).inflate(R.layout.item_series_activity, parent,false);
return new MyViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof MyViewHolder){
final Movies currentMovie = movies.get(position);
final MyViewHolder myholder = (MyViewHolder) holder;
Glide.with(context)
.load(currentMovie.getResim())
.into(myholder.movieImage);
}
else if (holder instanceof MyViewBanner){
final MyViewBanner myBanner = (MyViewBanner) holder;
AdRequest adRequest = new AdRequest.Builder().build();
myBanner.adView.loadAd(adRequest);
}
}
#Override
public int getItemCount() {
return movies.size() + 1;
}
#Override
public int getItemViewType(int position) {
if(position == 2){
return BANNER;
}
return ITEM;
}
}
My Activity
JsonArrayRequest arrayRequest = new JsonArrayRequest(murl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.i("log-",jsonArray.toString());
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
users.add(new Movies(jsonObject.getString("link"),
jsonObject.getString("resim"),
"",jsonObject.getString("tip")));
}
catch(JSONException e) {
Log.i("log-","error"+e.getMessage());
}
}
moviesAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {...
}
});
Volley.newRequestQueue(this).add(arrayRequest);
My Logcat
Process: com.moktay.izliyoo, PID: 23423
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.moktay.izliyoo.list.SeriesActivityAdapter.onBindViewHolder(SeriesActivityAdapter.java:64)
Pass null in Arraylist at the position where you want to show ads in recyler view.
Suppose at 2 and 4 position you want ads simplly add null at those position and finally in itemViewType method check for
if(arraylist.get(position)==null)
{
return BANNER
}else{
return VIEWTYPE
}
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
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.
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