How can make other button disable when one is clicked android studio? - java

I have a scenario where I have 5 ImageView and when one ImageView is clicked i want to set other 4 ImageView as Disabled. Please help to get logic for that.
My Logic for this : when 1 image is click set other 4 imageView as disable but imageView.setClickable(false) is not working.
This Attached Image is a dialog box that appears when users wants to edit something from recycler view. Recycler view contains data like : "Amount", "Item name", "Price", "Expense Type" and expense type image is set to On corresponding to "Expense Type".
I am stuck in this moment. Please help me out to solve this.
I have attached my scenario images Please check it out.
Here's my code for this
public class MyAdapter extends FirebaseRecyclerAdapter<ExpenseModel, MyAdapter.MyViewHolder> {
Context context;
private int lastPosition = -1;
private String whichCategorySelected = "";
private int calImgClick = 0;
private int groceryClick = 0;
private int bikeClick = 0;
private int rentClick = 0;
private int foodsClick = 0;
private int beerClick = 0;
public MyAdapter(#NonNull FirebaseRecyclerOptions<ExpenseModel> options, Context context) {
super(options);
this.context = context;
}
#SuppressLint("SetTextI18n")
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, #SuppressLint("RecyclerView") int position, #NonNull ExpenseModel model) {
holder.expenseItem.setText(model.getDescription());
holder.expenseAmount.setText("Rs. " + model.getAmount());
holder.expenseDate.setText(model.getTime());
String expType = model.getExType();
switch (expType) {
case "Beer":
holder.category.setBackgroundResource(R.drawable.beer);
break;
case "Grocery":
holder.category.setBackgroundResource(R.drawable.grocery);
break;
case "Bike":
holder.category.setBackgroundResource(R.drawable.bike);
break;
case "Rent":
holder.category.setBackgroundResource(R.drawable.rent);
break;
default:
holder.category.setBackgroundResource(R.drawable.fd);
break;
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPopMenuOnItemClicked(view, holder.getLayoutPosition(), model.getDescription(), model.getAmount(), model.getTime(), model.getExType());
}
});
}
private void showPopMenuOnItemClicked(View v, int pos, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
PopupMenu popupMenu = new PopupMenu(context, v);
popupMenu.getMenu().add("Edit");
popupMenu.getMenu().add("Delete");
popupMenu.getMenu().add("Delete All");
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getTitle().equals("Edit")) {
showUpdateDialogBox(v, getExpTitle, getExpAmt, getDate, whichCatSelected);
} else if (menuItem.getTitle().equals("Delete")) {
FirebaseReference.expenseReference(context)
.child(String.valueOf(getRef(pos).getKey()))
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(context.getApplicationContext(), "Delete everything", Toast.LENGTH_SHORT).show();
}
return true;
}
});
popupMenu.show();
}
#SuppressLint("ClickableViewAccessibility")
private void showUpdateDialogBox(View v, String getExpTitle, String getExpAmt, String getDate, String whichCatSelected) {
DialogPlus dialog = DialogPlus.newDialog(context)
.setContentHolder(new ViewHolder(R.layout.update_expense_layout))
.setExpanded(false)
.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogPlus dialog) {
onDismissSetClickCountToZero();
Utility.hideKeyboard(context, v);
}
})
.create();
View myView = dialog.getHolderView();
TextView update_expense_date = myView.findViewById(R.id.update_expense_date);
EditText update_expense_title = myView.findViewById(R.id.update_expense_title);
EditText update_expense_amount = myView.findViewById(R.id.update_expense_amount);
ImageView update_calendarImg = myView.findViewById(R.id.update_calendar);
Button update_button = myView.findViewById(R.id.update_btn);
LinearLayout linearLayout = myView.findViewById(R.id.update_linearCalenderLayout);
linearLayout.setVisibility(View.GONE);
CalendarView calendarView = myView.findViewById(R.id.update_calenderView);
LinearLayout categoryLayout = myView.findViewById(R.id.update_categoryIconsLayout);
TextView categoryTextView = myView.findViewById(R.id.update_selectCategory_heading);
update_expense_title.setText(getExpTitle);
update_expense_amount.setText(getExpAmt);
update_expense_date.setText(getDate);
ImageView beer = myView.findViewById(R.id.update_beer);
ImageView bike = myView.findViewById(R.id.update_bike);
ImageView grocery = myView.findViewById(R.id.update_grocery);
ImageView foods = myView.findViewById(R.id.update_foods);
ImageView rent = myView.findViewById(R.id.update_rent);
TextView desc_grocery = myView.findViewById(R.id.update_desc_grocery);
TextView desc_bike = myView.findViewById(R.id.update_desc_bike);
TextView desc_beer = myView.findViewById(R.id.update_desc_beer);
TextView desc_foods = myView.findViewById(R.id.update_desc_foods);
TextView desc_rent = myView.findViewById(R.id.update_desc_rent);
setIconVisible(whichCatSelected, bike, grocery, foods, beer, rent,
desc_bike, desc_grocery, desc_foods, desc_beer, desc_rent);
setWhichCategorySelected(whichCatSelected);
Toast.makeText(context, "Default select = " + getWhichCategorySelected() + " click = " + rentClick, Toast.LENGTH_SHORT).show();
update_calendarImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calImgClick++;
if (calImgClick >= 2) {
linearLayout.setVisibility(View.GONE);
categoryLayout.setVisibility(View.VISIBLE);
categoryTextView.setVisibility(View.VISIBLE);
calImgClick = 0;
} else {
linearLayout.setVisibility(View.VISIBLE);
categoryLayout.setVisibility(View.GONE);
categoryTextView.setVisibility(View.GONE);
}
}
});
rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Rent")){
rentClick ++;
if (rentClick >= 2) {
setWhichCategorySelected("");
rent.setBackgroundResource(R.drawable.rent_off);
desc_rent.setVisibility(View.GONE);
grocery.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Rent");
rent.setBackgroundResource(R.drawable.rent);
desc_rent.setVisibility(View.VISIBLE);
grocery.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
grocery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getWhichCategorySelected().equals("") || getWhichCategorySelected().equals("Grocery")){
groceryClick ++;
if (groceryClick >= 2) {
setWhichCategorySelected("");
grocery.setBackgroundResource(R.drawable.grocery_off);
desc_grocery.setVisibility(View.GONE);
rent.setClickable(true);
bike.setClickable(true);
foods.setClickable(true);
beer.setClickable(true);
rentClick = 0;
} else {
setWhichCategorySelected("Grocery");
grocery.setBackgroundResource(R.drawable.grocery);
desc_grocery.setVisibility(View.VISIBLE);
rent.setClickable(false);
bike.setClickable(false);
foods.setClickable(false);
beer.setClickable(false);
}
}else {
Toast.makeText(context, "Category is selected " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(context, "whichCategorySelected = " + getWhichCategorySelected(), Toast.LENGTH_SHORT).show();
}
});
update_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateChildren(update_expense_amount, update_expense_title, update_expense_date, whichCatSelected);
}
});
dialog.show();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view, parent, false);
return new MyViewHolder(v);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView expenseItem, expenseAmount, expenseDate;
ImageView category;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
expenseItem = itemView.findViewById(R.id.recyclerItemView);
expenseAmount = itemView.findViewById(R.id.recyclerAmountView);
expenseDate = itemView.findViewById(R.id.recyclerDateView);
category = itemView.findViewById(R.id.recyclerCategory);
}
}

Related

How to highlight a selected RecyclerView item and use its values in Activity

I have a list of words with translations in RecyclerView. I want the selected word to be highlighted, but at the same time I could use these values in Activity. I can highlight selected values or use the values of a selected item, but the combination of the both fails.
Please, maybe You see where I am wrong and can help solve my problem.
p.s. Please don’t judge me for the not enough clean code and my English, I’m learning. :)
MyListActivity.java
public class MyListActivity extends AppCompatActivity {
public ArrayList<MyWord> myWordList = new ArrayList<>();
SelectData sd = new SelectData();
int wordId;
String word;
String translation;
public RecyclerView mRecycleView;
public MyAdapter mAdapter;
public RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list);
sd.selectMyWords(myWordList);
buildRecycleView();
Button btnInsert = findViewById(R.id.mywords_button_insert);
Button btnEdit = findViewById(R.id.mywords_button_edit);
Button btnDelete = findViewById(R.id.mywords_button_delete);
Button btnMain = findViewById(R.id.mywords_button_backttomain);
mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
// **This is my selected item values**
wordId = myWordList.get(position).getWordId();
word = myWordList.get(position).getWord();
translation = myWordList.get(position).getTranslation();
Toast.makeText(MyListActivity.this, "Selected -> " + word, Toast.LENGTH_SHORT).show();
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(word == null)) {
Intent intentInsert = new Intent(MyListActivity.this, InsertActivity.class);
intentInsert.putExtra("W", word);
intentInsert.putExtra("TR", translation);
intentInsert.putExtra("ACTION", "ED");
startActivity(intentInsert);
} else {
Toast.makeText(MyListActivity.this, "Select word", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void buildRecycleView(){
mRecycleView = findViewById(R.id.mywords_RecycleView);
mRecycleView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MyAdapter(myWordList);
mRecycleView.setLayoutManager(mLayoutManager);
mRecycleView.setAdapter(mAdapter);
if (myWordList.isEmpty()){
Toast.makeText(this, "word list is empty", Toast.LENGTH_SHORT).show();
}
}
}
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<MyWord> mMyWordList;
private OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewEN;
public TextView mTextViewLT;
public ImageView imageViewLearned;
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public MyAdapter(ArrayList<MyWord> myWordList){
mMyWordList = myWordList;
}
int selectedItem = -1;
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_view_layout, parent, false);
MyViewHolder mvh = new MyViewHolder(v, mListener);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, final int position) {
MyWord currentMyWord = mMyWordList.get(position);
holder.mTextViewEN.setText(currentMyWord.getWord());
holder.mTextViewLT.setText(currentMyWord.getTranslation());
// TODO - START (select item highlight) - if I activate highlighting, the assignment of values no longer works in MyListActivity.
/* holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = position;
notifyDataSetChanged();
}
});
if (selectedItem == position) {
holder.itemView.setBackgroundColor(Color.parseColor("#C0C0C0"));
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#F8F8F8"));
} */
//TODO -END
}
#Override
public int getItemCount() {
return mMyWordList.size();
}
}
Looks like your commented code would overwrite your click listener with one that only hightlights. Try combining them:
public MyViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mTextViewEN = itemView.findViewById(R.id.myList_textView_word);
mTextViewLT = itemView.findViewById(R.id.myList_textView_translation);
imageViewLearned = itemView.findViewById(R.id.iV_learned);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
selectedItem = position;
notifyDataSetChanged();
listener.onItemClick(position);
}
}
}
});
}

how to Add urlimage to AdapterViewPager from MainActivity - AndroidX

I want to add the URLimage to AdapterViewPager from the MainActivity in AndroidX but I am not sure how to do this.
This is my AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/"
};
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return image_url.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
And this is my MainActivity.java
//ViewPager
public class ViewPagerTask extends TimerTask {
#Override
public void run() {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() < viewPager.getAdapter().getCount()-1){
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
I am not sure how to add the URLimage to AdapterViewPager from MainActivity in AndroidX? How do I solve this problem? Thanks you in advance.
//UPDATED//
AdapterViewPagerHot adapterViewPagerHotX = new AdapterViewPagerHot(getActivity());
adapterViewPagerHotX.setUrls(new String[]{"https://i.chzbgr.com/full/8803531264/hD42E57C6/"});
AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[];
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public int getCount() {
return image_url.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
Got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.indofun.android.indojoy.Adapters.Adapter_ViewPagerHot.AdapterViewPagerHot.setUrls(java.lang.String[])' on a null object reference
at com.indofun.android.indojoy.Support.TabHotFragment.onCreateView(TabHotFragment.java:117)
//UPDATED2//
AdapterViewPager.java
public class AdapterViewPagerHot extends PagerAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
/*private Integer[] images = {R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720,R.drawable.catnrobot,R.drawable.kleptocats,R.drawable.magiccat,R.drawable.flyingcat};*/
public String image_url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/"
};
public AdapterViewPagerHot(Context context) {
this.mContext = context;
}
#Override
public int getCount() {
return image_url.length;
}
public void setUrls(String[] list){
this.image_url = list;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public View vi;
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = layoutInflater.inflate(R.layout.item_viewpagerdisplay, null);
final Context sContext = mContext;
ImageView imageView = vi.findViewById(R.id.imageView);
final ImageView ICONHotViewPagerSaving = vi.findViewById(R.id.ICON_HotViewPagerSaving);
/*imageView.setImageResource(images[position]);*/
Glide.with(sContext).load(image_url[position]).into(imageView);
vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(sContext, "Slide" + (position+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});
final Boolean[] boollatestnewssaving = {false};
ICONHotViewPagerSaving.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boollatestnewssaving[0] == true){
Toast.makeText(v.getContext(), "Turn Off Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_off);
boollatestnewssaving[0] = false;
/*updateSavedNewsSaving("update_newssaving", id, false);*/
} else if(boollatestnewssaving[0] == false) {
Toast.makeText(v.getContext(), "Turn On Saved News ", Toast.LENGTH_SHORT).show();
ICONHotViewPagerSaving.setImageResource(R.drawable.saved_on);
boollatestnewssaving[0] = true;
/*updateSavedNewsSaving("update_newssaving", id, true);*/
}
}
});
ViewPager vp = (ViewPager) container;
vp.addView(vi, 0);
return vi;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
//TabHotActivity.java
public class TabHotFragment extends Fragment {
//SetupMainActivity
public static MainActivity mainActivity_;
//ADS GOOGLE Initialize Ads Banner
private AdView mAdView;
//AutoSlide
/*FlipperLayout flipper;*/
//ViewPager
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
AdapterViewPagerHot adapterViewPagerHot;
//1
ArrayList<ModelSectionHotTrendingNews> modelSectionHotTrendingNews = new ArrayList<ModelSectionHotTrendingNews>();
AdapterSectionHotTrendingNews adapterSectionHotTrendingNews;
//2
ArrayList<ModelSectionHotLatestNews> modelSectionHotLatestNews = new ArrayList<ModelSectionHotLatestNews>();
AdapterSectionHotLatestNews adapterSectionHotLatestNews;
//3
ArrayList<ModelSectionHotFollowing> modelSectionHotFollowings = new ArrayList<ModelSectionHotFollowing>();
AdapterSectionHotFollowing adapterSectionHotFollowing;
//ModelData
List<ModelSingleHotTrendingNews> modelSingleHotTrendingNews;
List<ModelSingleHotLatestNews> modelSingleHotLatestNews;
List<ModelSingleHotFollowing> modelSingleHotFollowings;
//EVENT BUS
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredHighlight event) {
getHighlightMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredTrending event) {
getTrendingMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MainActivity.EventStoredLatest event) {
getLatestMainActivity(event.SendTotalThread, event.SendDummyID, event.SendDummyTitle, event.SendDummyPublishTime, event.SendDummyImageOri, event.SendDummyShortDescription);
}
public void getHighlightMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniHighlightXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
public void getTrendingMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniTrendingXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
public void getLatestMainActivity(int ReceivedTotalThread, int ReceivedDummyID, String ReceivedDummyTitle, String ReceivedDummyPublishTime, String ReceivedDummyImageOri, String ReceivedDummyShortDescription){
Toast.makeText(getActivity(), "IniLatestXTotalThread="+ReceivedTotalThread+", DummyID="+ReceivedDummyID+", DummyTitle="+ReceivedDummyTitle+", DummyPublishTime="+ReceivedDummyPublishTime+", DummyImageOri="+ReceivedDummyImageOri+", DummyShortDescription"+ReceivedDummyShortDescription, Toast.LENGTH_LONG).show();
AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
}
View v;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_tabhot, container, false);
//Clear Model that Created before When Fragment Opened Again
modelSectionHotLatestNews.clear();
modelSectionHotTrendingNews.clear();
modelSectionHotFollowings.clear();
/*setContentView(R.layout.activity_main);*/
String[] strArray = new String[]{"https://scx1.b-cdn.net/csz/news/800/2019/1-nasastessmis.jpg"};
adapterViewPagerHot.setUrls(strArray);
/*//AA
//Autoslide
flipper=v.findViewById(R.id.flipper);
setLayout();*/
//ViewPager
viewPager = (ViewPager) v.findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout) v.findViewById(R.id.SliderDots);
adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
viewPager.setAdapter(adapterViewPagerHot);
dotscount = adapterViewPagerHot.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getActivity());
dots[i].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageResource(R.drawable.nonactive_dot);
}
dots[position].setImageResource(R.drawable.active_dot);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Timer timer = new Timer();
//This is going to start after 2 second and will repeat on every 8 seconds time interval.
timer.scheduleAtFixedRate(new ViewPagerTask(), 5000, 8000);
//1
createDummyData1();
RecyclerView RecyclerViewSingleHotTrendingNews = v.findViewById(R.id.RecyclerView_Single_HotTrendingNews);
RecyclerViewSingleHotTrendingNews.setHasFixedSize(true);
adapterSectionHotTrendingNews = new AdapterSectionHotTrendingNews(getActivity(), modelSectionHotTrendingNews);
RecyclerViewSingleHotTrendingNews.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotTrendingNews.setAdapter(adapterSectionHotTrendingNews);
//Optimized
RecyclerViewSingleHotTrendingNews.setHasFixedSize(true);
RecyclerViewSingleHotTrendingNews.setItemViewCacheSize(20);
//2
createDummyData2();
RecyclerView RecyclerViewSingleHotLatestNews = v.findViewById(R.id.RecyclerView_Single_HotLatestNews);
RecyclerViewSingleHotLatestNews.setHasFixedSize(true);
adapterSectionHotLatestNews = new AdapterSectionHotLatestNews(getActivity(), modelSectionHotLatestNews);
RecyclerViewSingleHotLatestNews.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotLatestNews.setAdapter(adapterSectionHotLatestNews);
//Optimized
RecyclerViewSingleHotLatestNews.setHasFixedSize(true);
RecyclerViewSingleHotLatestNews.setItemViewCacheSize(20);
//3
createDummyData3();
RecyclerView RecyclerViewSingleHotFollowing = v.findViewById(R.id.RecyclerView_Single_HotFollowing);
RecyclerViewSingleHotFollowing.setHasFixedSize(true);
adapterSectionHotFollowing = new AdapterSectionHotFollowing(getActivity(), modelSectionHotFollowings);
RecyclerViewSingleHotFollowing.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
RecyclerViewSingleHotFollowing.setAdapter(adapterSectionHotFollowing);
//Optimized
RecyclerViewSingleHotFollowing.setHasFixedSize(true);
RecyclerViewSingleHotFollowing.setItemViewCacheSize(20);
String y = getString(R.string.AdmobID_Core);
//ADS GOOGLE Kode Inti
MobileAds.initialize(getActivity(), getString(R.string.AdmobID_Core));
mAdView = v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
/*AdRequest adRequestBanner = new AdRequest.Builder()
.addTestDevice("2019091717123202457")
.build();*/
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Toast.makeText(getActivity(),"RKAd Loaded",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getActivity(),"Ad Failed to load / Doesn't get Ads Right Now",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
Toast.makeText(getActivity(),"Ad Opened",Toast.LENGTH_SHORT).show();
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdLeftApplication() {
Toast.makeText(getActivity(),"Ad Left Application",Toast.LENGTH_SHORT).show();
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
Toast.makeText(getActivity(),"RKAd Closed",Toast.LENGTH_SHORT).show();
// Code to be executed when when the user is about to return
// to the app after tapping on an ad.
}
});
//INI COBA HIT HIGHLIGHT
//SetDataProfile
Button BTNHighlight;
BTNHighlight = v.findViewById(R.id.BTN_Highlight);
BTNHighlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Highlight");
}
}
});
//INI COBA HIT TRENDING
//SetDataProfile
Button BTNTrending;
BTNTrending = v.findViewById(R.id.BTN_Trending);
BTNTrending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Trending");
}
}
});
//INI COBA HIT LATEST
//SetDataProfile
Button BTNLatest;
BTNLatest = v.findViewById(R.id.BTN_Latest);
BTNLatest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainActivity_ != null) {
mainActivity_.rncryptorALLDEWA("Latest");
}
}
});
/* ViewPager vp = v.findViewById(R.id.ViewPager);
vp.addView(vi, 0);
final AdapterViewPagerHot adapterViewPagerHot = new AdapterViewPagerHot(getActivity());
adapterViewPagerHot.vi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Slide" + (adapterViewPagerHot.getCount()+1) + "Clicked", Toast.LENGTH_SHORT).show();
}
});*/
return v;
}
/*//Autoslide
private void setLayout(){
String url[] = new String[]{
"https://i.chzbgr.com/full/8803531264/hD42E57C6/",
"https://i.pinimg.com/originals/d2/fc/5a/d2fc5ab22b9b9d13320b3a8be48625ad.jpg",
"https://i.ytimg.com/vi/5rOtNmdKgsE/maxresdefault.jpg"
};
for(int i=0; i<url.length; i++){
FlipperView view = new FlipperView(getActivity().getBaseContext());
view.setImageUrl(url[i])
.setDescription("Gambar"+ (i+1));
flipper.addFlipperView(view);
view.setOnFlipperClickListener(new FlipperView.OnFlipperClickListener() {
#Override
public void onFlipperClick(FlipperView flipperView) {
Toast.makeText(getActivity(), ""+(flipper.getCurrentPagePosition()+1), Toast.LENGTH_SHORT).show();
}
});
}
}*/
//ViewPager
public class ViewPagerTask extends TimerTask {
#Override
public void run() {
Activity activity = getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() < viewPager.getAdapter().getCount()-1){
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
/*public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Section " + i);
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 7; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);
}
}*/
public void createDummyData1() {
ModelSectionHotTrendingNews modelSectionHotTrendingNewsX = new ModelSectionHotTrendingNews();
modelSectionHotTrendingNewsX.setHeaderTitle("TRENDING NEWS");
ArrayList<ModelSingleHotTrendingNews> modelSingleHotTrendingNews = new ArrayList<ModelSingleHotTrendingNews>();
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(1, "20 Mei 2019", "Citing personal differences with his human co-hosts, Watson announced it would be leaving the show last Friday.", R.drawable.magiccat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(2, "21 Mei 2019", "They developed superpowers after years of drinking from a lead-poisoned water supply. But just having incredible abilities doesn't make them superheroes. Not yet.", R.drawable.cat_mermaid_cartoon_grumpy_cat_94004_1280x720, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(3, "22 Mei 2019", "Facing increased competition from niche restaurants targeting millennials, the Echo Park Chipotle announced today it would become the nation’s first “Rat Cafe,”", R.drawable.kleptocats, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(4, "23 Mei 2019", "The world rejoiced today as The Apprentice's Donald J. Trump brokered a deal with all nations that would create everlasting peace and prospetiy", R.drawable.catnrobot, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(5, "24 Mei 2019", "Portsmouth, Australia. Alcohol Quality Inspectorate (AQI) was alarmed after Harry Taylor (23), reported a reportedly poisoned alcohol batch", R.drawable.flyingcat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(6, "25 Mei 2019", "A popular local beer produce was almost forced to stop bottling beer in their branch in Portsmouth", R.drawable.bubblesthecat, false, "x53535", "No Error"));
modelSingleHotTrendingNews.add(new ModelSingleHotTrendingNews(7, "26 Mei 2019", "The man went to a house party with his friends and did not waive from drinking alcohol. After drinking one beer", R.drawable.catnrobot, false, "x53535", "No Error"));
modelSectionHotTrendingNewsX.setAllItemsInSection(modelSingleHotTrendingNews);
modelSectionHotTrendingNews.add(modelSectionHotTrendingNewsX);
}
modelSectionHotLatestNewsX.setAllItemsInSection(modelSingleHotLatestNews);
modelSectionHotLatestNews.add(modelSectionHotLatestNewsX);
}
//EVENTBUS
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
}
Error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.indofun.android.indojoy.Adapters.Adapter_ViewPagerHot.AdapterViewPagerHot.setUrls(java.lang.String[])' on a null object reference
at com.indofun.android.indojoy.Support.TabHotFragment.onCreateView(TabHotFragment.java:131)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at
you can create a method for that in your adapter
public class AdapterViewPagerHot extends PagerAdapter {
private String [] urlList;
...
public void setUrls(String[] list){
this.urlList = list;
}
...
}
you can call this method on your adapter instance in your activity:
viewPager.setUrls(/*your URL list*/);
I put setImageUrl inside Adapter because it will be executed first if I try to make another function it will crash
public AdapterViewPagerHot(Context context, String[] list) {
this.mContext = context;
this.image_url = list;
}

Android RecyclerView item selection issue

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.
Here is the adapter class of my RecyclerView
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder>{
private int mItemSelected=-1;
private List<DmLiveQuiz> questionList;
DmLiveQuiz questionsList; // DmLiveQuiz questionsList
private Context context; //context
final DataHolder dh=new DataHolder();
public List<Integer> myResponse= new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
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());
holder.optA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_border);
holder.optB.setBackgroundResource(R.drawable.button_question_style);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.optA.setBackgroundResource(R.drawable.button_question_style);
holder.optB.setBackgroundResource(R.drawable.button_border);
holder.optC.setBackgroundResource(R.drawable.button_question_style);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optC.setOnClickListener(new View.OnClickListener() {
#Override
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_border);
holder.optD.setBackgroundResource(R.drawable.button_question_style);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.optD.setOnClickListener(new View.OnClickListener() {
#Override
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_border);
Toast toast = Toast.makeText(context, "Position :"+holder.getAdapterPosition(), Toast.LENGTH_SHORT);
toast.show();
}
});
holder.tvClear.setOnClickListener(new View.OnClickListener() {
#Override
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);
}
});
}
#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);
optB=(Button)itemView.findViewById(R.id.buttonOptionB);
optC=(Button)itemView.findViewById(R.id.buttonOptionC);
optD=(Button)itemView.findViewById(R.id.buttonOptionD);
tvClear=(TextView)itemView.findViewById(R.id.tvClearSelection);
}
}
}
The only problem I am facing is the auto selection of unanswered options.
Please help me out in selecting the selected option only not the ones which are not selected. Thanks in advance.
The views will be reused in your RecyclerView and hence you are having such a problem. In your case, you might consider having another array which stores the answers of your quizzes and can keep track of every item in your RecyclerView.
I would like to suggest modifying your adapter like the following. I have commented in some places. Hope that helps you to understand your problem.
public class LiveTestAdapter extends RecyclerView.Adapter<LiveTestAdapter.CustomViewHolder> {
private int mItemSelected = -1;
private List<DmLiveQuiz> questionList;
private int[] answerList; // Get a list of your answers here.
private DmLiveQuiz questionsList;
private Context context;
final DataHolder dh = new DataHolder();
public List<Integer> myResponse = new ArrayList<Integer>();
public int qno;
public String myQno;
public int afterSub;
DataHolder dataHolder;
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
Toast.makeText(context, "Position :" + holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
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() {
#Override
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);
optB = (Button) itemView.findViewById(R.id.buttonOptionB);
optC = (Button) itemView.findViewById(R.id.buttonOptionC);
optD = (Button) itemView.findViewById(R.id.buttonOptionD);
tvClear = (TextView) itemView.findViewById(R.id.tvClearSelection);
}
}
}
Update - Please check that I have added setQuestionList function in the adapter. Please use this function to set your question list. Because, I think while initializing your adapter, the question list which is being passed is having a size of zero.

RecyclerView getting wrong position When Apply Search with Search Filter

I use RecyclerView and I have implemented Search Filter on it and i am facing a problem here
After I search when I press on item I get wrong position not one I searched it please help me to solve this problem
For example item number 2 name "Android" after search "android" the position go number one .. why get this problem ? .. thank you
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Filter
TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().equals("")){
initAdapter();
} else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
private void initAdapter(){
adapter.listItems.clear();
for (int i = 0; i < 10; i++) {
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
}
adapter.notifyDataSetChanged();
}
private void searchItem(String itemname){
int resultCount = 0;
adapter.listItems.clear();
for (int i = 0; i < tempListItems.size(); i++){
if (tempListItems.get(i).getTitle().contains(itemname)){
listItems.add(new RecyclerItem("Item " + (i + 1), "Welcome to Torisan channel, this is description of item " + (i+1)));
resultCount ++;
}
}
if (resultCount == 0){
showToast();
}
adapter.notifyDataSetChanged();
}
public void showToast() {
// Set the toast and duration
int toastDurationInMilliSeconds = 1000;
mToastToShow = Toast.makeText(this, "No results found.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public List<RecyclerItem> listItems;
private Context mContext;
public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setTag(getAdapterPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = Integer.parse(v.getTag().toString());
if (position == 0) {
Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();
}
if (position == 1) {
Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();
}
}
});
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
holder.txtDescription.setText(itemList.getDescription());
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Display option menu
PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
popupMenu.inflate(R.menu.option_menu);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_item_save:
Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.mnu_item_delete:
//Delete item
Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
listItems.remove(position);
notifyDataSetChanged();
break;
default:
break;
}
return false;
}
});
popupMenu.show();
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button buttoncalling;
public TextView txtTitle;
public TextView txtDescription;
public TextView txtOptionDigit;
public ViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
buttoncalling = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
buttoncalling.setOnClickListener(this);
}
#Override
public void onClick(View view) {
}
}
}
Please use this
for (int i = 0; i < tempListItems.size(); i++) {
if (listItems.get(getAdapterPosition()).getName().equals(tempListItems.get(i).getName())) {
int selectedPos = i; //SelectedPos is that index
break;
}
}

android: how to increase number of quantity of an item in the cart

when user adds same item in the cart for multiple times it should be add that item only for one time and increase number of quantity of that item but in my case whole item is added for each time.
below is cart activity:
public class CartActivity extends AppCompatActivity implements CartAdapter.OnCartDataChangeListener {
DatabaseHandler helper;
public static List<ProductModel> dbList;
RecyclerView mRecyclerView;
Toolbar toolbar;
Button btnCheckout, btnContinueShopping;
public TextView tvTotalNoOfItems, tvTotalPrice;
String productVaiantId;
String selectedProductId;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
productVaiantId = getIntent().getStringExtra("variant_id");
selectedProductId = getIntent().getStringExtra("product_id");
Bundle extras = getIntent().getExtras();
if (extras != null) {
productVaiantId = extras.getString("variant_id");
selectedProductId = extras.getString("product_id");
}
toolbar = (Toolbar) findViewById(R.id.customToolBar);
setSupportActionBar(toolbar);
setTitle("Check-out");
toolbar.setTitleTextColor(Color.BLACK);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
helper = new DatabaseHandler(this);
dbList = new ArrayList<ProductModel>();
dbList = helper.getDataFromDB();
mRecyclerView = (RecyclerView) findViewById(R.id.rv_cart_item_list);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mLayoutManager = new LinearLayoutManager(this) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(CartActivity.this) {
private static final float SPEED = 300f;// Change this value (default=25f)
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return SPEED / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
mAdapter = new CartAdapter(this, dbList, this);
tvTotalNoOfItems = (TextView) findViewById(R.id.tvTotalCartItems);
tvTotalPrice = (TextView) findViewById(R.id.tvTotalCartItemsPrice);
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new SlideInUpAnimator());
btnContinueShopping = (Button) findViewById(R.id.btnBackToProductActivity);
btnContinueShopping.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCollectionActivity = new Intent(CartActivity.this, CollectionActivity.class);
startActivity(launchCollectionActivity);
finish();
}
});
btnCheckout = (Button) findViewById(R.id.btn_checkout);
btnCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAdapter.getItemCount() == 0){
Toast.makeText(CartActivity.this,"Your cart is empty",Toast.LENGTH_SHORT).show();
}
else {
Intent launchCheckoutActivity = new Intent(CartActivity.this, CheckoutActivity.class);
startActivity(launchCheckoutActivity);
} }
});
}
#Override
public void dataChanged() {
tvTotalNoOfItems.setText(dbList.size() + "");
double totalPrice = 0.0;
for (int i = 0; i < dbList.size(); i++) {
totalPrice += Double.parseDouble(dbList.get(i).getPrice());
}
tvTotalPrice.setText("" + totalPrice);
}
}
below is cart adapter:
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
public interface OnCartDataChangeListener{
public void dataChanged();
}
private OnCartDataChangeListener listener;
private List<ProductView.Data> productData = Collections.emptyList();
static List<ProductModel> productModelList;
static Context context;
DatabaseHandler mDatabaseHandler;
public CartAdapter(Context context, List<ProductModel> dbList, OnCartDataChangeListener listener ){
this.productModelList = new ArrayList<ProductModel>();
this.context = context;
this.productModelList = dbList;
mDatabaseHandler = new DatabaseHandler( context );
this.listener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View cartListView = inflater.inflate(R.layout.list_item_cart, parent, false);
// Return a new holder instance
ViewHolder viewHolder = new ViewHolder(context,cartListView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.tvProductName.setText(productModelList.get(position).getTitle());
holder.tvProductPrice.setText(productModelList.get(position).getPrice());
Glide
.with(context)
.load(productModelList.get(position).getImageUrl())
.placeholder(R.drawable.placeholder_loading)
.into(holder.imgProduct);
holder.tvSize.setText(productModelList.get(position).getSize());
holder.tvProductQuantity.setText(Integer.toString(productModelList.get(position).getQuantity()));
holder.tvColor.setText(productModelList.get(position).getColor());
holder.imgDelete.setClickable(true);
holder.imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String idForDelete = String.valueOf(productModelList.get(position).getVariantId());
mDatabaseHandler.deleteARow(idForDelete);
productModelList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,productModelList.size());
CartActivity.dbList = productModelList;
listener.dataChanged();
}
});
}
#Override
public int getItemCount() {
return productModelList.size();
}
public void Refresh(ArrayList<ProductModel> datas) {
this.productModelList.clear();
this.productModelList.addAll(datas);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvProductName, tvProductPrice, tvProductQuantity, tvColor,
tvSize;
ImageView imgProduct;
ImageButton imgDelete;
Context context;
public ViewHolder(Context mContext, View itemView) {
super(itemView);
this.tvProductName = (TextView) itemView.findViewById(R.id.tv_cart_product_name);
this.tvProductPrice = (TextView) itemView.findViewById(R.id.tv_cart_product_price);
this.tvProductQuantity = (TextView) itemView.findViewById(R.id.tv_cart_product_Quantity);
this.imgProduct = (ImageView) itemView.findViewById(R.id.img_cart_item_product);
this.tvColor = (TextView) itemView.findViewById(R.id.tv_color);
this.tvSize = (TextView) itemView.findViewById(R.id.tv_size);
this.imgDelete = (ImageButton) itemView.findViewById(R.id.img_cart_delete);
// store the context ///
this.context = mContext;
}
}
and this snippet is from previous activity from i get product when addToCart button is pressed:
btn_addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String title = tv_productName.getText().toString();
String price = tv_productPrice.getText().toString();
String status = tv_productStatus.getText().toString();
String imageUrl = productImageList.get(0);
String productColor = String.valueOf(sp_productColor.getSelectedItem());
String productSize = String.valueOf(sp_productSize.getSelectedItem());
String productQuantity = String.valueOf(tv_productQuantity.getText());
final String productId = response.data().node().asProduct().id();
final String variantId = response.data().node().asProduct().variants().edges().get(0).node().id();
// save into database
helper = new DatabaseHandler(ProductDetailActivity.this);
helper.insertIntoDB(variantId, title, price, imageUrl, status, productSize, productQuantity, productColor);
// display snackbar to navigate to cart activity
Snackbar.make(view, R.string.snackbar_text, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action, new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchCartActivity = new Intent(ProductDetailActivity.this, CartActivity.class);
// adding the first product and its first variant to the cart
launchCartActivity.putExtra("product_id", productId);
launchCartActivity.putExtra("variant_id", variantId);
startActivity(launchCartActivity);
finish();
}
}).show();
}
});
You should apply check . If the item already exists in the cart then only increase the quantity
Try it like this.
private boolean isAlreadyInCart(int targetItemId) {
boolean isAlreadyInCart = false;
for (int i = 0; i < itemIds.length; i++) {
if (targetItemId == itemIds[i]) {
isAlreadyInCart = true;
break;
}
}
return isAlreadyInCart;
}
Now call use this method like this.
if (!isAlreadyInCart(itemId)) {
// TODO: add item to cart
} else {
// TODO: increase quantity
}

Categories

Resources