I am designing a live quiz app that fetches data from server and question are displayed in a RecyclerView that contains a question and four options. Now when I select one option for a given question, it is selected properly but at the same time, the corresponding option for other question is selected automatically.
Screenshot of the item selection issue is the following.
I have designed Data Model Class and RecylerView Adapter (with the help of #Reaz Murshed) but have been stuck with the code
My Data Model Class is :
//DmLiveQuiz
public class DmLiveQuiz {
String testId;
int questionId;
String question;
String optA;
String optB;
String optC;
String optD;
String answer;
String explain;
...
}
My Adapter Class is //LiveTestAdapter
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder> {
private List<DmLiveQuiz> questionList;
private int[] answerList; // Get a list of your answers here.
private DmLiveQuiz questionsList;
private Context context;
public List<Integer> myResponse = new ArrayList<Integer>();
public int qno;
public LiveTestAdapter(List<DmLiveQuiz> questionList, Context context) {
this.questionList = questionList;
this.context = context;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.live_quiz_display_format, parent, false);
return new CustomViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
questionsList = questionList.get(holder.getAdapterPosition());
holder.tvQNo.setText(questionsList.getQuestionId() + "");
holder.tvquestion.getLayoutParams().width = LinearLayout.LayoutParams.WRAP_CONTENT;
holder.tvquestion.setText(questionsList.getQuestion());
holder.optA.setText(questionsList.getOptA());
holder.optB.setText(questionsList.getOptB());
holder.optC.setText(questionsList.getOptC());
holder.optD.setText(questionsList.getOptD());
// Now you need to modify the backgrounds of your option buttons like the following.
if (answerList[position] == 1) holder.optA.setBackgroundResource(R.drawable.button_border);
else holder.optA.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 2) holder.optB.setBackgroundResource(R.drawable.button_border);
else holder.optB.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 3) holder.optC.setBackgroundResource(R.drawable.button_border);
else holder.optC.setBackgroundResource(R.drawable.button_question_style);
if (answerList[position] == 4) holder.optD.setBackgroundResource(R.drawable.button_border);
else holder.optD.setBackgroundResource(R.drawable.button_question_style);
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
answerList[position] = 1; // Selected first option which is A
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optB.setBackgroundResource(R.drawable.button_border);
answerList[position] = 2; // Selected second option which is B
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optC.setBackgroundResource(R.drawable.button_border);
answerList[position] = 3; // Selected third option which is C
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optD.setBackgroundResource(R.drawable.button_border);
answerList[position] = 4; // Selected fourth option which is D
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
answerList[position] = 0; // Clear the value in the answerList
}
});
}
// Use this function to set the question list in the adapter
public void setQuestionList(List<DmLiveQuiz> questionList) {
this.questionList = questionList;
this.answerList = new int[questionList.size()]; // This initializes the answer list having the same size as the question list
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return questionList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
TextView tvquestion, tvClear, tvQNo;
Button optA, optB, optC, optD;
public CustomViewHolder(View itemView) {
super(itemView);
tvQNo = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestionNo);
tvquestion = (TextView) itemView.findViewById(R.id.tvLiveQuizQuestion);
optA = (Button) itemView.findViewById(R.id.buttonOptionA);
...///
}
}
}
And The Activity where Recyclerview is implemented is
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewLiveTest);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
quizList = new ArrayList<>();
adapter = new LiveTestAdapter(quizList, getApplicationContext());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
getData();
......
The method for fetching JSON data is getdata() as given below which fetches data from server correctly...
private void getData() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(quiz_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
DmLiveQuiz liveQuiz = new DmLiveQuiz();
...
...
quizList.add(liveQuiz);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
..........
}
Now When I run App, it shows index=0 i.e. ArrayOutOfIndexException is generated.. I am not able to call public void setQuestionList(List<DmLiveQuiz> questionList) method of LiveQuizAdapter class from my activity.. Please Help
Initially you are setting empty list in the adapter. After getting value from JsonArrayRequest then need to update adapter using new list.
Update onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
DmLiveQuiz dmLiveQuiz= questionList.get(position);
if(dmLiveQuiz!=null){
// do whatever you want. put all code here.}
}
Update your adapter:
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
// put all code here
quizList.add(liveQuiz);}
adapter.setQuestionList(quizList);
adapter.notifyDataSetChanged();
}
you have to add a boolean value in DmLiveQuiz model class :-
boolean isSelected ;
and then set a check in your adapter while your are showing the answer is selected or not :-
if(DmLiveQuiz.isSelectd){
// this is the selected answer
}else {
// in case don't selected
}
and change the boolean value on adapter item Click
Related
I have recyclerview where I am displaying the items with Itemname, Itemrate and quantity of the items which is increased and decreased by +/- buttons respectively. now, i want to get all the values from each item of the recyclerview and send it over the server or save it to local database so how to achieve this.?
//This is My Adapter Class
public class TeaListAdapter extends RecyclerView.Adapter {
//private int num=0;
private List<TeaListPOJO> teaItemList;
private Context mContext;
private Cursor cursor;
int comboCount;
HashMap<Object,Integer> selectedMap = new HashMap ();
private String ItemName;
private String itemrate;
private String qty;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tvitemName, tvitemRate,tvcount; //number
public ImageView ivItemImg,ivPlus,ivMinus;
public Button btnIncrease,btnDecrease;
RecyclerView.ViewHolder holder;
public MyViewHolder(View view) {
super(view);
tvitemName = (TextView) view.findViewById(R.id.txt_item_name);
tvitemRate = (TextView) view.findViewById(R.id.txt_item_price);
ivItemImg= (ImageView) view.findViewById (R.id.iv_item);
ivPlus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_plus);
ivMinus=(ImageView) view.findViewById (R.id.row_view_final_order_iv_minus);
tvcount=(TextView) view.findViewById (R.id.row_view_final_order_tv_count);
}
}
public TeaListAdapter(List<TeaListPOJO> teaItemList) {
this.mContext=mContext;
this.cursor=cursor;
this.teaItemList = teaItemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_placeorder_items, parent, false);
return new MyViewHolder (itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
TeaListPOJO tealist = teaItemList.get(position);
holder.tvitemName.setText(tealist.getItemName ());
holder.tvitemRate.setText(AppConstants.INDIAN_RUPEE_SIGN.concat (tealist.getItemRate ()));
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
//count++;
count = Integer.parseInt(holder.tvcount.getText().toString());
holder.tvcount.setText(String.valueOf(count+ 1));
}
});
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
int count=0;
try{
count = Integer.parseInt(holder.tvcount.getText().toString());
}
catch(Exception e) {
count = 0;
}
if(count>0) {
//count--;
count = Integer.parseInt (holder.tvcount.getText ().toString ());
holder.tvcount.setText (String.valueOf (count - 1));
}
}
});
holder.itemView.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
}
});
/* Intent intent = new Intent (mContext, PlaceOrderActivity.class);
// intent.putExtra("quantity",Integer.parseInt(quantity.getText().toString()));
intent.putExtra ("quantity", qty);
intent.putExtra ("item", ItemName);
intent.putExtra ("itemrate", itemrate);
ItemName = holder.tvitemName.getText().toString();
qty = holder.tvcount.getText().toString();
itemrate=holder.tvitemRate.getText ().toString ();
Log.e("rate",itemrate);
Log.e("qty",qty);*/
byte[] decodedString = new byte[0];
try {
decodedString = Base64.decode(tealist.getImageStr(), Base64.DEFAULT);
// tenantModelPOJO.setLogo(decodedString);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivItemImg.setImageBitmap(Bitmap.createScaledBitmap(bmp, 50, 50,false));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return teaItemList.size();
}
}
//This is My Activity Class
public class PlaceOrderActivity extends AppCompatActivity implements AppConstants, View.OnClickListener, WLAPIcalls.OnAPICallCompleteListener {
private List<TeaListPOJO> teaList = new ArrayList<> ();
private RecyclerView recyclerView;
private TeaListAdapter mAdapter;
private View view;
private Button btnPlaceorder;
EditText edtmsg;
public String str;
private Context mContext = PlaceOrderActivity.this;
private int itemCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_place_order);
str=getIntent ().getStringExtra ("quantity");
edtmsg= (EditText) view.findViewById (R.id.et_message);
edtmsg.setText (str);
setRecyclerView (view);
getallTeaItems ();
}
List<TeaListPOJO> getTeaItemList(String str) {
Gson gson = new Gson ();
Type listType = new TypeToken<List<TeaListPOJO>> () {
}.getType ();
List<TeaListPOJO> myModelList = gson.fromJson (str, listType);
return myModelList;
}
private List<TeaListPOJO> getallTeaItems() {
if (new AppCommonMethods (mContext).isNetworkAvailable ()) {
WLAPIcalls mAPIcall = new WLAPIcalls (mContext, getString (R.string.getTeaItem), this);
mAPIcall.GetTeaItemList ();
} else {
Toast.makeText (mContext, R.string.no_internet, Toast.LENGTH_SHORT).show ();
}
return null;
}
void setRecyclerView(View view) {
recyclerView = (RecyclerView) findViewById (R.id.recycler_view);
mAdapter = new TeaListAdapter (teaList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager (getApplicationContext ());
recyclerView.setLayoutManager (mLayoutManager);
recyclerView.setItemAnimator (new DefaultItemAnimator ());
recyclerView.setAdapter (mAdapter);
}
#Override
public void onClick(View view) {
}
#Override
public void onAPICallCompleteListner(Object item, String flag, String result) throws JSONException {
if (getString (R.string.getTeaItem).equals (flag)) {
Log.e ("Result", result);
teaList = getTeaItemList (result);
setRecyclerView (view);
}
}
}
Add an extra property in your TeaListPOJO model say count when you press +/- button you have to set count in your model like you set the count in your text view. So in your adapter you have TeaListPOJO list. Show when you want to send data to server get list of TeaListPOJO and also you have list of count.
In the adapter set a call to the API to change the value in the DB.
You shouldn't need to pass the entire data, usually you'll be able to just update that one object you're looking at by passing the id in the URL.
e.g.
https://hostname.domain/api/object/ID
Use a PUT request and pass the info from the object in that row.
If you're creating the back-end of this too then I'd highly suggest you set this up as passing the entire dataset for all rows is not exactly an ideal solution.
If these didn't exist in the first place and they are all created from being in the app then have a button on your main activity that saves the list, then pass the entire list to an API call, most likely will need to parse the data into JSON.
I assume here that if the latter is the case that you have created these objects in a class.
the TeaListPOJO should also need a field for storing the count. Increment or decrement the count value when user's clicks on the + or - button and display the count value to the textview, instead of directly diplaying.
class TeaListPojo{
private int count;
.....
public int getCount()
return this.count
}
public void setCount(int count)
{
this.count = count;
}
}
Here is the code for updating the count textview
public void onBindViewHolder(final MyViewHolder holder, final int position) {
TeaListPOJO tealist = teaItemList.get(position);
.....
.....
holder.ivPlus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
tealist.setCount( tealist.getCount() + 1);
holder.tvcount.setText(String.valueOf(count));
}
});
holder.ivMinus.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick(View view) {
tealist.setCount(tealist.getCount() - 1)
holder.tvcount.setText (String.valueOf (count));
}
}
});
}
I have a sectioned recyclerview implemented which works great. I want to include a checkbox in all my items which show up under a section.The thing I want to implement now is to allow user to check one checkbox at a time. I have tried radiobutton also but the problem stays the same as I am unable to get hold of the listeners.
I have searched for it on stackoverflow but I could not get it work. getTag() gives me a null pointer exception and I have also tried keeping a selectedPosition variable and trying but I could not get the getTag() to work.
public class HeaderRecyclerViewSection extends StatelessSection {
private static final String TAG = HeaderRecyclerViewSection.class.getSimpleName();
private String title;
private List<RestaurauntMenuItemDetail> list;
private List<RestaurauntMenuItemDetail> checkedList;
private int selectedPosition = -1;
public HeaderRecyclerViewSection(String title, List<RestaurauntMenuItemDetail> list) {
super(R.layout.section_ex1_header, R.layout.layout_section_item);
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, final int position) {
final ItemViewHolder iHolder = (ItemViewHolder)holder;
iHolder.variationItemName.setText(list.get(position).getVariationItemName());
iHolder.variationItemPrice.setText(Double.toString(list.get(position).getVariationItemPrice()));
iHolder.checkBox.setOnCheckedChangeListener(null);
iHolder.checkBox.setChecked(list.get(position).isSelected());
Log.i("EXECUTED AGAIN","AGAIN");
iHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(selectedPosition == position){
list.get(selectedPosition).setSelected(false);
iHolder.checkBox.setChecked(list.get(selectedPosition).isSelected());
}
list.get(position).setSelected(b);
Log.i("POSITION is",Integer.toString(position));
Log.i("B Is",Boolean.toString(b));
selectedPosition = position;
}
});
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder hHolder = (HeaderViewHolder)holder;
hHolder.headerTitle.setText(title);
}
}
My ItemHolder class:
public class ItemViewHolder extends RecyclerView.ViewHolder{
public TextView variationItemName;
public TextView variationItemPrice;
CheckBox checkBox;
public ItemViewHolder(View itemView) {
super(itemView);
variationItemName = (TextView) itemView.findViewById(R.id.variationItemName);
variationItemPrice = (TextView) itemView.findViewById(R.id.variationItemPrice);
checkBox = itemView.findViewById(R.id.checkBox2);
}
}
What i am trying to achieve is to allow user to be able to select one checkbox under a certain section.
EDIT 1:
This is how currently my screen looks either with radiobutton or checkbox.
EDIT 2:
I changed my code as follows which lets me to check one radiobutton at a time. The thing is that when you click on the last item in the recycler view list , the radiobutton does not get checked and if it does then when you scroll up , it vanishes.
#Override
public void onBindItemViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ItemViewHolder iHolder = (ItemViewHolder)holder;
iHolder.variationItemName.setText(list.get(position).getVariationItemName());
iHolder.variationItemPrice.setText(Double.toString(list.get(position).getVariationItemPrice()));
iHolder.variationItemPrice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("I WAS CLICKED","ITEM PRICE WAS CLICKED");
}
});
iHolder.radioButton.setChecked(list.get(position).isSelected());
iHolder.radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("I was pressed","BUtton");
RadioButton rb = (RadioButton) view;
if(rb.isChecked()){
Log.i("CONTAINS",Boolean.toString(radioButtonList.contains(rb)));
if(position >= radioButtonList.size()){
radioButtonList.add(rb);
rb.setChecked(true);
list.get(position).setSelected(true);
}else{
}
//list.get(position).setSelected(true);
}
for (int i = 0; i < radioButtonList.size(); i++) {
RadioButton nrb = radioButtonList.get(i);
if(i != position){
if(nrb.isChecked()){
nrb.setChecked(false);
list.get(i).setSelected(false);
}
}
}
Log.i("RADIO LIST",Integer.toString(radioButtonList.size()));
for (int i = 0; i < radioButtonList.size(); i++) {
Log.i("RADIO CHECKED",Boolean.toString(radioButtonList.get(i).isChecked()));
}
Log.i("CURRENT POST",Integer.toString(position));
for (int i = 0; i < list.size() ; i++) {
Log.i("POST",Boolean.toString(list.get(i).isSelected()));
}
}
});
}
My Activity Class:
public class RestaurauntMenuItemDetailActivity extends AppCompatActivity implements RestaurauntMenuItemDetailInterfaceHandler{
private static List<RestaurauntMenuItemDetail> restaurauntMenuItemDetailList = new LinkedList<>();
RestaurauntMenuItemDetailFetchAPI restaurauntMenuItemDetailFetchAPI;
String restaurauntSlug;
String menuSlug;
int menuId;
int variationCount;
List<String> variationNamesList;
private RecyclerView sectionHeader;
private SectionedRecyclerViewAdapter sectionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restauraunt_menu_item_detail);
//
// sectionAdapter = new SectionedRecyclerViewAdapter();
restaurauntMenuItemDetailFetchAPI = new RestaurauntMenuItemDetailFetchAPI(this,this);
restaurauntSlug = getIntent().getExtras().getString("restaurauntSlug");
menuSlug = getIntent().getExtras().getString("menuSlug");
menuId = getIntent().getExtras().getInt("menuId");
restaurauntMenuItemDetailFetchAPI.prepareURL(restaurauntSlug,menuSlug,menuId);
restaurauntMenuItemDetailFetchAPI.fetchMenuItemDetail();
}
#Override
public void restaurauntMenuItemDetailListDownloadTaskCompleted(List<RestaurauntMenuItemDetail> result,int variationCount,List<String> variationNames) {
restaurauntMenuItemDetailList = result;
this.variationCount = variationCount;
variationNamesList = variationNames;
sectionHeader = (RecyclerView)findViewById(R.id.menuItemDetailRecyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(RestaurauntMenuItemDetailActivity.this);
sectionHeader.setLayoutManager(linearLayoutManager);
sectionHeader.setHasFixedSize(true);
// HeaderRecyclerViewSection secondSection = new HeaderRecyclerViewSection("Second Section", restaurauntMenuItemDetailList);
// HeaderRecyclerViewSection thirdSection = new HeaderRecyclerViewSection("Third Section", restaurauntMenuItemDetailList);
sectionAdapter = new SectionedRecyclerViewAdapter();
for(int i=0; i < variationNamesList.size(); i++){
String variationName = variationNames.get(i);
addSectionToAdapter(variationName,sectionAdapter);
sectionHeader.setAdapter(sectionAdapter);
}
// sectionAdapter.addSection(secondSection);
// sectionAdapter.addSection(thirdSection);
// initRecyclerView();
}
private void addSectionToAdapter(String variationName, SectionedRecyclerViewAdapter sectionAdapter){
List<RestaurauntMenuItemDetail> l1 = new ArrayList<>();
for (int i = 0; i < restaurauntMenuItemDetailList.size() ; i++) {
if(restaurauntMenuItemDetailList.get(i).getVariationCategory().equals(variationName)){
l1.add(restaurauntMenuItemDetailList.get(i));
}
}
HeaderRecyclerViewSection firstSection = new HeaderRecyclerViewSection(variationName, l1,sectionAdapter);
sectionAdapter.addSection(firstSection);
}
}
Try this. It worked for me. Might work for you as well. Just replace your OnCheckedChangeListener code with this one:
iHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton compoundButton,boolean b){
if(compoundButton.isPressed()){
// click is performed
for(RestaurauntMenuItemDetail item:list){
item.setSelected(false);
}
list.get(holder.getAdapterPosition()).setSelected(b);
notifyDataSetChanged();
}
}
});
I looked at a lot of other questions posted by users and got a little help by the comments provided here. What i actually wanted was to able to check one radio box at a time and secondly, when we scroll down in our recycler view either check box from the radio button vanished or it was wrong.
We need to keep a boolean variable in our class which holds our object and we can set it to false by default. Generate the getters and setters. The code is as follows:
The list goes at the top, just in case.
List<RadioButton> radioButtonList = new ArrayList<>();
private int selectedPosition = -1;
#Override
public void onBindItemViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ItemViewHolder iHolder = (ItemViewHolder)holder;
final RestaurauntMenuItemDetail r = list.get(position);
iHolder.radioButton.setTag(position);
iHolder.radioButton.setOnCheckedChangeListener(null);
iHolder.radioButton.setChecked(r.getSelected());
iHolder.radioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos = (Integer) iHolder.radioButton.getTag();
RadioButton rb = (RadioButton) v;
if(radioButtonList.isEmpty()){
radioButtonList.add(rb);
rb.setChecked(true);
list.get(pos).setSelected(true);
selectedPosition = pos;
}else{
RadioButton nrb = radioButtonList.get(0);
if(nrb.isChecked()){
Log.i("NEW RB BUTTON WAS CHECKED", "CHECKED NRB");
nrb.setChecked(false);
list.get(selectedPosition).setSelected(false);
}
radioButtonList.remove(0);
radioButtonList.add(rb);
rb.setChecked(true);
list.get(pos).setSelected(true);
selectedPosition = pos;
}
}
});
I have a recyclerview list of items and in the adapter, I have a button for adding an item as favorite to an active android database like below code:
viewholder.favoriteWP_IV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Favorites favorites = new Favorites(); // Model class for db crud
favorites.setFavoritesId(UUID.randomUUID().toString());
favorites.setLargeImgURL(pixaImages.getLargeImgURL());
favorites.setPreviewImgURL(pixaImages.getPreviewImgURL());
favorites.setImageId(favorites.getImageId());
favorites.save();
Log.d(TAG, "Fav_id:\t" + favorites.getId());
Log.d(TAG, "Favorites Id:\t" + favorites.getFavoritesId());
//TODO: 6/13/2018 Fix Duplicate Favorite WP
Toast.makeText(context, "Added to Favorites", Toast.LENGTH_SHORT).show();
}
});
and in my FavoritesActivity, I have retrieved all the items and shown them in a recyclerview like below code:
public List<Favorites> getAllFavorites() {
return new Select()
.all()
.from(Favorites.class)
.orderBy("favorites_id ASC")
.execute();
}
private void getFavorites() {
favsRV.setHasFixedSize(true);
favsRV.setLayoutManager(new LinearLayoutManager(this));
AdapterHeaderItem headerItem = new AdapterHeaderItem();
headerItem.setHeaderIcon(R.drawable.drawer_header_trimmed);
headerItem.setHeaderTitle("you can toggle through your favorite wallpapers using the wallpaper widget on your home screen");
objectList.add(headerItem);
//itemsList = getAllFavorites();
Favorites favorites = new Favorites();
for (int i = 0; i < getAllFavorites().size(); i++) {
favorites.setFavoritesId(getAllFavorites().get(i).getFavoritesId());
favorites.setLargeImgURL(getAllFavorites().get(i).getLargeImgURL());
favorites.setPreviewImgURL(getAllFavorites().get(i).getPreviewImgURL());
favorites.setImageId(getAllFavorites().get(i).getImageId());
Log.d(TAG, "All Favs Ids:\t" + getAllFavorites().get(i).getFavoritesId());
objectList.add(favorites);
}
Log.d(TAG, "Favorites List Size:\t" + objectList.size());
adapter = new FavoritesAdapter(this, objectList);
favsRV.setAdapter(adapter);
}
The problem here is that the item clicked on to be saved is not the one actually saved and when the list has multiple items, it retrieves duplicate copies of same item.
Previously, my adapter wasn't having a header and it was working fine but when I added the header to adapter, I had to change from List<Favorites> to List<Object> to enable me add the header items to the view.
In my activity, I have retrieved all the records while using old adapter code by this line itemsList = getAllFavorites(); but with the new adapter code, I have to use an object to store items in list.
I have tried this Favorites favs = (Favorites) itemsList = getAllFavorites(); but the app crashed, only other option I had was to do this and save in object list:
Favorites favorites = new Favorites();
for (int i = 0; i < getAllFavorites().size(); i++) {
favorites.setFavoritesId(getAllFavorites().get(i).getFavoritesId());
favorites.setLargeImgURL(getAllFavorites().get(i).getLargeImgURL());
favorites.setPreviewImgURL(getAllFavorites().get(i).getPreviewImgURL());
favorites.setImageId(getAllFavorites().get(i).getImageId());
Log.d(TAG, "All Favs Ids:\t" + getAllFavorites().get(i).getFavoritesId());
objectList.add(favorites);
}
Here's my model class:
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
#Table(name = "favorites")
public class Favorites extends Model{
#Column(name = "favorites_id")
public String favoritesId;
#Column(name = "image_id")
public int imageId;
#Column(name = "large_img_url")
public String largeImgURL;
#Column(name = "preview_img")
public String previewImgURL;
public Favorites() { }
public Favorites(String favoritesId, int imageId, String largeImgURL, String previewImgURL) {
this.favoritesId = favoritesId;
this.imageId = imageId;
this.largeImgURL = largeImgURL;
this.previewImgURL = previewImgURL;
}
public String getFavoritesId() {
return favoritesId;
}
public void setFavoritesId(String favoritesId) {
this.favoritesId = favoritesId;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getLargeImgURL() {
return largeImgURL;
}
public void setLargeImgURL(String largeImgURL) {
this.largeImgURL = largeImgURL;
}
public String getPreviewImgURL() {
return previewImgURL;
}
public void setPreviewImgURL(String previewImgURL) {
this.previewImgURL = previewImgURL;
}
}
but this code block gives me for a list of three items, one item duplicated three times. I think it's because of the change in code. The adapter works well but in activity, I am fetching wrong results.
Here's my adapter code:
public class FavoritesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = FavoritesAdapter.class.getSimpleName();
private final Context context;
private List<Object> itemsList;
public static final int HEADER_VIEW = 0;
public static final int ITEMS_VIEW = 1;
public FavoritesAdapter(Context context, List<Object> itemsList) {
this.context = context;
this.itemsList = itemsList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == HEADER_VIEW) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.app_adapter_header_layout, parent, false);
return new AdapterHeaderItemViewHolder(view);
} else if (viewType == ITEMS_VIEW) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.favorites_item_layout, parent, false);
return new FavoritesViewHolder(view);
}
throw new RuntimeException("No matching viewTypes");
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof AdapterHeaderItemViewHolder) {
AdapterHeaderItem header = (AdapterHeaderItem) itemsList.get(position);
((AdapterHeaderItemViewHolder) holder).headerTitleTV.setText(header.getHeaderTitle());
Picasso.with(context)
.load(header.getHeaderIcon())
.placeholder(R.drawable.drawer_header_trimmed)
.into(((AdapterHeaderItemViewHolder) holder).headerIconIV);
} else if (holder instanceof FavoritesViewHolder) {
final Favorites favorites = (Favorites) itemsList.get(position);
Picasso.with(context)
.load(favorites.getLargeImgURL())
.placeholder(R.mipmap.ic_launcher)
.into(((FavoritesViewHolder) holder).favoriteWPImg);
((FavoritesViewHolder) holder).removeTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Adapter VH Posn:\t" + holder.getAdapterPosition());
String fav_id = favorites.getFavoritesId();
Log.d(TAG, "Favorites+id:\t" + fav_id);
removeAtPosition(holder.getAdapterPosition(), fav_id);
}
});
((FavoritesViewHolder) holder).previewTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent previewIntent = new Intent(context, PreviewWallPaperActivity.class);
previewIntent.putExtra("fav_id", favorites.getFavoritesId());
previewIntent.putExtra("large_url", favorites.getLargeImgURL());
previewIntent.putExtra("preview_url", favorites.getPreviewImgURL());
context.startActivity(previewIntent);
}
});
}
}
private void removeAtPosition(int position, String id) {
Log.d(TAG, "id in method:\t" + id);
new Delete()
.from(Favorites.class)
.where("favorites_id=?", id)
.execute();
Log.d(TAG, "Favorite Removed from db");
itemsList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, itemsList.size());
Toast.makeText(context, "Removed From Favorites", Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return HEADER_VIEW;
return ITEMS_VIEW;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}
I think the problem lies here with the loop and inserting into the adapter list:
itemsList = getAllFavorites();
Favorites favorites = new Favorites();
for (int i = 0; i < getAllFavorites().size(); i++) {
favorites.setFavoritesId(getAllFavorites().get(i).getFavoritesId());
favorites.setLargeImgURL(getAllFavorites().get(i).getLargeImgURL());
favorites.setPreviewImgURL(getAllFavorites().get(i).getPreviewImgURL());
favorites.setImageId(getAllFavorites().get(i).getImageId());
Log.d(TAG, "All Favs Ids:\t" + getAllFavorites().get(i).getFavoritesId());
objectList.add(favorites);
}
//objectList.add(itemsList); // I have tried adding the first list of Favorite model class into the adapter list but it gives `classcast exception: Model class can't be cast to ArrayList`
Can anyone help me understand why same item is coming multiple times? Thanks.
I have successfully to get next page of post using Blogger's API, but i can't achieve the smooth scrolling of recyclerview, it look lagging.
I have tried using recyclerViewData.setNestedScrollingEnabled(false) and adapter.notifyDataSetChanged() but still doesn't work.
My point is How to achieve smooth of recyclerview. Any suggestion will be appreciate. thank is advance.
Here is my code
private void getData() {
showLoading(true);
final Call<ResponseBlogPost> postList = apiService.getListPost(GlobalVariable.APP_KEY);
postList.enqueue(new Callback<ResponseBlogPost>() {
#Override
public void onResponse(Call<ResponseBlogPost> call, Response<ResponseBlogPost> response) {
showLoading(false);
ResponseBlogPost responseBlogPost = response.body();
initDataView(responseBlogPost);
}
#Override
public void onFailure(Call<ResponseBlogPost> call, Throwable t) {
showLoading(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void initDataView(ResponseBlogPost listpost){
GlobalFunction.saveString(this,GlobalVariable.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
itemsList.addAll(listpost.getItems());
adapter = new MainAdapter(itemsList) {
#Override
public void load() {
if(nextPageToken==null){
return;
}
getNextListPost();
}
};
recyclerViewData.setAdapter(adapter);
recyclerViewData.setHasFixedSize(true);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,1);
staggeredGridLayoutManager.setGapStrategy(0);
recyclerViewData.setLayoutManager(staggeredGridLayoutManager);
}
private void getNextListPost(){
showLoading(true);
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
Call<ResponseBlogPost> call = apiService.getNexPageListPost(GlobalVariable.APP_KEY,nextPageToken);
call.enqueue(new Callback<ResponseBlogPost>() {
#Override
public void onResponse(Call<ResponseBlogPost> call, Response<ResponseBlogPost> response) {
showLoading(false);
ResponseBlogPost responseModel = response.body();
if(nextPageToken!=null){
initDataView2(responseModel);
}else{
Toast.makeText(MainActivity.this, "tidak ada data lagi ya", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBlogPost> call, Throwable t) {
showLoading(false);
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void initDataView2(ResponseBlogPost listpost){
GlobalFunction.saveString(this,GlobalVariable.TOKEN_PAGINATION, listpost.getNextPageToken());
final String nextPageToken = GlobalFunction.getStrings(this, GlobalVariable.TOKEN_PAGINATION);
itemsList.addAll(listpost.getItems());
adapter = new MainAdapter(itemsList) {
#Override
public void load() {
if(nextPageToken!=null){
getNextListPost();
}
}
};
recyclerViewData.setAdapter(adapter);
recyclerViewData.setHasFixedSize(true);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, 1);
staggeredGridLayoutManager.setGapStrategy(0);
recyclerViewData.setLayoutManager(staggeredGridLayoutManager);
}
My Adapter Code :
public abstract class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder>{
private List<BlogPostModel> responseBlogPost;
public MainAdapter(List<BlogPostModel> responseBlogPost) {
this.responseBlogPost = responseBlogPost;
}
public abstract void load();
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main,parent,false);
return new MainViewHolder(view);
}
#Override
public void onBindViewHolder(final MainViewHolder holder, int position) {
final BlogPostModel model = responseBlogPost.get(position);
ArrayList<String> urlImage = pullLinks(model.getContent());
String firstImage = "";
for (int i = 0; i < urlImage.size(); i++) {
firstImage = urlImage.get(1);
GlideCustomLoading.setImageFromURL(holder.itemView.getContext(), urlImage.get(0)
,holder.avLoadingIndicatorView, holder.ivItemPost,holder.tvFailedLoadImage);
}
holder.tvTitleItemPost.setText(model.getTitle());
final String finalFirstImage = firstImage;
holder.llItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = String.valueOf(model.getId());
DetailPostActivity.start(holder.itemView.getContext(), id, finalFirstImage, model.getTitle(), model.getUrl());
}
});
if(position>=getItemCount()-1){
load();
}
}
#Override
public int getItemCount() {
return responseBlogPost.size();
}
public class MainViewHolder extends RecyclerView.ViewHolder{
CardView cardViewItemPost;
ImageView ivItemPost;
TextView tvTitleItemPost;
AVLoadingIndicatorView avLoadingIndicatorView;
TextView tvFailedLoadImage;
LinearLayout llItem;
public MainViewHolder(View itemView) {
super(itemView);
cardViewItemPost = itemView.findViewById(R.id.cardview_item_post);
ivItemPost = itemView.findViewById(R.id.iv_image_post);
tvTitleItemPost = itemView.findViewById(R.id.tv_title_post);
avLoadingIndicatorView = itemView.findViewById(R.id.avi_load);
tvFailedLoadImage = itemView.findViewById(R.id.tv_gagal_menampilkan_gambar);
llItem = itemView.findViewById(R.id.ll_item_post);
}
}
private ArrayList pullLinks(String html) {
ArrayList links = new ArrayList();
Elements srcs = Jsoup.parse(html).select("[src]"); //get All tags containing "src"
for (int i = 0; i < srcs.size(); i++) {
links.add(srcs.get(i).attr("abs:src")); // get links of selected tags
}
return links;
}
}
While I'm not familiar with Jsoup I'm reasonably confident that it's the source of your scroll lag.
You are calling the method pullLinks in your onBindViewHolder method which is called every time a new view is added to your RecyclerView. I'm assuming pullLinks does some pretty intensive work that takes some time to complete.
What you would be better off doing is to add all of the data to each item in your responseBlogPost List before loading it in to the adapter.
Here is my doubt when i click recyclerview item need to get task id which i saved in sqlite how can i do this for example when i click recycler view need to pass that value to next page and need update that value how can i do this so far what i have tried is:
public class Task extends Fragment {
private static final String MY_PREFERENCE_KEY = "yogan";
private List<Model_Task_List> model_task_lists;
private RecyclerView recyclerView;
Task_List_Adapter taskadapter;
private RecyclerView.LayoutManager layoutManager;
SharedPreferences sharedPreferences;
private RecyclerView.Adapter adapter;
RequestQueue yog;
String user_id;
AppController app;
RequestQueue queue;
String Url;
Task_DB task_db = null;
Database_SF_APP database_sf_app;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(layoutManager);
if (model_task_lists == null) {
model_task_lists = new ArrayList<Model_Task_List>();
}
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
int hour=c.get(Calendar.HOUR_OF_DAY);
String hours=Integer.toString(hour);
database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
int count=database_sf_app.getTaskCount();
sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
user_id = sharedPreferences.getString("user_id", null);
model_task_lists=database_sf_app.getTaskListById(user_id);
taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
recyclerView.setAdapter(taskadapter);
if(taskadapter!=null){
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
}
});
}
queue = Volley.newRequestQueue(getContext());
Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/Task/" + user_id +"/" +null+"/"+hours;
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.POST, Url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("TaskResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Task_List modelobj = new Model_Task_List();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));
modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
database_sf_app.insertorUpdate(modelobj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
//Creating request queue
queue.add(jsonObjRequest);
}
//sync operation
//a union b
//a server
//b local storage
//a only - insert local
//b only - send to server
//a = b do nothing
//result
//bind
return view;
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop() {
super.onStop();
}
}
Here is my TaskAdapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class Task_List_Adapter extends RecyclerView.Adapter<Task_List_Adapter.MyViewHolder> {
private List<Model_Task_List> dataSet;
private Context context;
private static data yog;
Model_Task_List modelTaskList=new Model_Task_List();
public void remove(int position)
{
dataSet.remove(position);
notifyItemRemoved(position);
}
public void edit(int position){
dataSet.set(position, modelTaskList);
notifyItemChanged(position);
}
public void setOnItemClickListener(data listener) {
this.yog = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
// Model_Task_List Model_Task_List=new Model_Task_List();
TextView textname;
TextView textaddress;
TextView textphnum;
TextView textdegree;
TextView textemail;
ImageView call;
data datas;
public MyViewHolder(final View itemView) {
super(itemView);
this.textname = (TextView) itemView.findViewById(R.id.subject);
this.textaddress = (TextView) itemView.findViewById(R.id.username);
this.textphnum = (TextView) itemView.findViewById(R.id.status);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yog!=null){
yog.yog(itemView,getLayoutPosition());
}
}
});
// this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public interface data
{
void yog(View v,int position);
}
public Task_List_Adapter(List<Model_Task_List> data,Context context) {
this.dataSet = data;
this.context=context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.task_list_view, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
TextView textViewName = holder.textname;
TextView textViewaddress = holder.textaddress;
TextView textViewphnum = holder.textphnum;
TextView textdegree = holder.textdegree;
TextView textemail=holder.textemail;
textViewName.setText("Subject:"+dataSet.get(position).getSubject());
textViewaddress.setText("DueDate"+dataSet.get(position).getUserName());
textViewphnum.setText("Status:"+dataSet.get(position).getTaskStatus());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
IS it right way to get id:
taskadapter.setOnItemClickListener(new Task_List_Adapter.data() {
#Override
public void yog(View v, int position) {
Model_Task_List model_task_list=(Model_Task_List)model_task_lists.get(position);
String yog=model_task_list.getSubject().toString();
int yogeshs=model_task_list.getTaskID();
String yogan=Integer.toString(yogeshs);
Toast.makeText(getContext(),yogan,Toast.LENGTH_SHORT).show();
}
});
}
Where i make recyclerview clickable how to get id of sqlite when i click and need to pass the value to next page
The object you are displaying in recyclerview ,
in your case that code must be in TaskAdapter,
put id in that object so when you click on it you will get that object so retrieve ID from that object
clickedObjecj.getId();
defining onClick in the onBindViewHolder is not a good pratice
the correct way is that declare a interface in the adapter class and implement it on the Activity , Using interface we can pass the value
Steps 1:
Decalre Listener for the OnItemClickListener interface
private OnItemClickListener mListener;
Step 2 : declare an interface , this interface will forward our click and data from adapter to our activity
public interface OnItemClickListener {
void onItemClick(int elementId);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Step 3 : define the on click on ViewHolder and pass the id
//Assigning on click listener on the item and passing the ID value of the item
itemView.setOnClickListener(new View.OnClickListener() { // we can handle the click as like we do in normal
#Override
public void onClick(View v) {
if (mListener != null) {
int elementId = dataSet.get(getAdapterPosition()).getTaskID(); // Get the id of the item on that position
mListener.onItemClick(elementId); // we catch the id on the item view then pass it over the interface and then to our activity
}
}
});
Step 4: implement TaskAdapter.OnItemClickListener in the activity
Step 6: onItemClick method you will recive the value
#Override
public void onItemClick(int itemId) {
Log.d(TAG, "onItemClick: "+String.valueOf(itemId));
}
first you have to set Cursor position into clicked one
Ex: Cursor products <- storing a set of data
to set Cursor to clicked position for example a position value from RecyclerView click event
products.moveToPosition(position);
then use getString as usual
String name = products.getString(products.getColumnIndex("NAME"));
hope it may help
Hmm, my problem just change setOnClickListener to setOnLongClickListener
i declare puplic static int posit in my Adapter
Second in onBindViewHolder of Adapter, i call:
holder.layout_item.setOnLongClickListener(new View.OnLongClickListener() { #Override public boolean online(View view) { posit = arrayList.get(position).getId(); return false; } });
Next, on MainActivity, i want delete 1 object in sqlite
Boolean checkDeleteData = phamTuanVan_sqlite.deleteData(PhamTuanVan_Adapter.posit);
hope it may help