How to get rid of duplicates RecyclerView Adapter? - java

I have a universal Adapter with all states. I use it everywhere. But this class is very cumbersome, and does not comply with the principles of DRY
public class AdapterWithStates extends RecyclerView.Adapter {
private static final int STATE_NORMAL = 0;
public static final int STATE_LOADING = 1;
public static final int STATE_EMPTY = 3;
public static final int STATE_ERROR = 4;
public static final int STATE_ERROR_CONNECTION = 5;
private static final int TYPE_NORMAL = 1000;
private static final int TYPE_LOADING = 1001;
private static final int TYPE_LOADING_MORE = 1002;
private static final int TYPE_EMPTY = 1003;
private static final int TYPE_ERROR = 1004;
private static final int TYPE_ERROR_CONNECTION = 1005;
private static final int TYPE_ERROR_LOADING = 1006;
private static final int TYPE_ERROR_CONNECTION_LOADING = 1007;
private int state = STATE_LOADING;
private List<Specialist> specialistsList;
private Context context;
private boolean loading = false;
private AdapterListener mListener;
public AdapterWithStates(Context context,
List<Specialist> specialistsList,
AdapterListener adapterListener) {
this.specialistsList = specialistsList;
this.context = context;
this.mListener = adapterListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_LOADING:
return new ViewHolders.LoadingViewHolder(LayoutInflater.from(context)
.inflate(R.layout.loading_row, parent, false));
case TYPE_LOADING_MORE:
return new ViewHolders.LoadMoreProgressViewHolder(LayoutInflater.from(context)
.inflate(R.layout.load_more_row, parent, false));
case TYPE_EMPTY:
return new ViewHolders.EmptyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.error_empty_row, parent, false));
case TYPE_ERROR:
if (specialistsList.size() > 0) {
return new ViewHolders.LoadMoreProgressViewHolder(LayoutInflater.from(context)
.inflate(R.layout.load_more_row, parent, false));
} else {
return new ViewHolders.ErrorViewHolder(LayoutInflater.from(context)
.inflate(R.layout.error_row, parent, false));
}
case TYPE_ERROR_CONNECTION:
if (specialistsList.size() > 0) {
return new ViewHolders.LoadMoreProgressViewHolder(LayoutInflater.from(context)
.inflate(R.layout.load_more_row, parent, false));
} else {
return new ViewHolders.ErrorConnectionViewHolder(LayoutInflater.from(context)
.inflate(R.layout.error_connection_row, parent, false));
}
case TYPE_ERROR_LOADING:
return new ViewHolders.ErrorLoadMoreViewHolder(LayoutInflater.from(context)
.inflate(R.layout.error_load_more_row, parent, false));
case TYPE_ERROR_CONNECTION_LOADING:
return new ViewHolders.ErrorLoadMoreViewHolder(LayoutInflater.from(context)
.inflate(R.layout.error_connection_load_more_row, parent, false));
default:
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.specialist_short_layout_row, parent, false));
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolders.LoadingViewHolder) {
onBindLoadingViewHolder((ViewHolders.LoadingViewHolder) holder);
} else if (holder instanceof ViewHolders.LoadMoreProgressViewHolder) {
onBindLoadMoreViewHolder((ViewHolders.LoadMoreProgressViewHolder) holder, position);
} else if (holder instanceof ViewHolders.ErrorLoadMoreViewHolder) {
onBindErrorLoadMoreViewHolder((ViewHolders.ErrorLoadMoreViewHolder) holder, position);
} else if (holder instanceof ViewHolders.EmptyViewHolder) {
onBindEmptyViewHolder((ViewHolders.EmptyViewHolder) holder, position);
} else if (holder instanceof ViewHolders.ErrorViewHolder) {
onBindErrorViewHolder((ViewHolders.ErrorViewHolder) holder, position);
} else if (holder instanceof ViewHolders.ErrorConnectionViewHolder) {
onBindErrorConnectionViewHolder((ViewHolders.ErrorConnectionViewHolder) holder, position);
} else if (holder instanceof MyViewHolder) {
onBindDefaultViewHolder((MyViewHolder) holder, position);
}
}
private void onBindDefaultViewHolder(MyViewHolder holder, int position) {
Specialist specialist = specialistsList.get(position);
holder.mName.setText(specialist.getFullName());
holder.mService.setText(specialist.getSex());
holder.mRatingBar.setRating(specialist.getRating() != null ? Float.parseFloat(specialist.getRating()) : 0);
}
private void onBindErrorViewHolder(ViewHolders.ErrorViewHolder holder, final int position) {
holder.retryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null)
mListener.onRetryClickListener(position);
}
});
}
private void onBindErrorConnectionViewHolder(ViewHolders.ErrorConnectionViewHolder holder, final int position) {
holder.retryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null)
mListener.onRetryClickListener(position);
}
});
}
private void onBindEmptyViewHolder(ViewHolders.EmptyViewHolder holder, final int position) {
holder.mEmptyLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null)
mListener.onEmptyClickListener(position);
}
});
}
private void onBindLoadMoreViewHolder(ViewHolders.LoadMoreProgressViewHolder holder, final int position) {
holder.errorLayout.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.VISIBLE);
holder.progressBar.setIndeterminate(true);
if (!loading) {
if (mListener != null) {
mListener.onLoadMore(position);
}
loading = true;
}
}
private void onBindErrorLoadMoreViewHolder(ViewHolders.ErrorLoadMoreViewHolder holder, final int position) {
holder.retryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null)
mListener.onRetryClickListener(position);
}
});
}
private void onBindLoadingViewHolder(ViewHolders.LoadingViewHolder holder) {
holder.progressBar.setIndeterminate(true);
}
#Override
public int getItemCount() {
switch (state) {
case STATE_LOADING:
case STATE_EMPTY:
case STATE_ERROR_CONNECTION:
case STATE_ERROR:
if (specialistsList != null && specialistsList.size() != 0)
return specialistsList.size();
else
return 1;
default:
return specialistsList.size();
}
}
#Override
public int getItemViewType(int position) {
switch (state) {
case STATE_LOADING:
if (specialistsList.size() == 0)
return TYPE_LOADING;
else if (specialistsList.get(position) == null)
return TYPE_LOADING_MORE;
else
return TYPE_NORMAL;
case STATE_EMPTY:
return TYPE_EMPTY;
case STATE_ERROR:
if (specialistsList.size() == 0)
return TYPE_ERROR;
else if (specialistsList.get(position) == null)
return TYPE_ERROR_LOADING;
else
return TYPE_NORMAL;
case STATE_ERROR_CONNECTION:
if (specialistsList.size() == 0)
return TYPE_ERROR_CONNECTION;
else if (specialistsList.get(position) == null)
return TYPE_ERROR_CONNECTION_LOADING;
else
return TYPE_NORMAL;
default:
if (specialistsList.get(position) != null) {
return TYPE_NORMAL;
} else {
return TYPE_LOADING_MORE;
}
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
CardView mRoot;
TextView mName;
TextView mService;
RatingBar mRatingBar;
MyViewHolder(View view) {
super(view);
mRoot = view.findViewById(R.id.root_layout);
mName = view.findViewById(R.id.name_tv);
mService = view.findViewById(R.id.service_tv);
mRatingBar = view.findViewById(R.id.ratingBar);
mRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mListener != null)
mListener.onItemClickListener(getAdapterPosition());
}
});
}
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
notifyDataSetChanged();
}
public void update(List<Specialist> newList) {
specialistsList = newList;
notifyItemInserted(specialistsList.size());
}
public void removeLastItem() {
if (specialistsList != null && specialistsList.size() != 0)
specialistsList.remove(specialistsList.size() - 1);
notifyDataSetChanged();
}
public void setLoaded() {
state = STATE_NORMAL;
loading = false;
}
}
Is it possible to reduce or inherit by leaving the onBindDefaultViewHolder method and the MyViewHolder class for implementation?

You could make your SpecialistAdapter abstract:
public abstract class SpecialistAdapter extends RecyclerView.Adapter {
//...
public abstract RecyclerView.ViewHolder makeViewHolder();
}
Then, when you extend SpecialistAdapter, you'll still need to implement onBindViewHolder(), as well as the new makeViewHolder() method.
Under onCreateViewHolder(), you can call makeViewHolder() instead of creating a new MyViewHolder instance:
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
vh = makeViewHolder();
} else {
View v = LayoutInflater.from(context).inflate(R.layout.loading_row, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}

Related

Android survey app with multiple viewholders and viewpager

in my app I'm creating a survey with multiple question types like radio button, checkboxes, dropdown, photo, stars, textbox. Survey has a number of pages and for this case I'm using a viewpager.
Radio buttons and checkboxes are generated dynamically, questions can have a comment field and some them can have optional fields.
In each page I have a recyclerview where I display types of questions. The problem is when I want to save the data, it is not working. Now I have an adapter for ViewPager and another one for recyclerview. In each view holder of recyclerview I have to save the data to Sqlite database when I click finish button in the viewpager. I'm trying to use an interface to communicate but the data are not saved correctly.
Here what I have on my viewpager adapter:
public class SurveyPagerAdapter extends PagerAdapter {
private final List<RecyclerView> mViews;
private final List<Page> mPages;
private final Context mContext;
private final AppCompatActivity mActivity;
private final ViewPager viewPager;
// ArrayList<SurveyListLines> surveyLinesList;
ArrayList<Integer> requiredQuestions;
private final Location location;
private final MutableLiveData<Integer> liveData = new MutableLiveData<>();
SettingsManager manager;
String code;
int headerId;
private final onSaveCallback onSaveCallback;
private final boolean hasAnswers;
private List<Answers> answersList;
private final String clientCode;
int questionId;
private static OnButtonSendPressedCallback mButtonSendPressedCallback;
public static void setOnButtonSendPressedCallback(OnButtonSendPressedCallback onButtonSendPressedCallback) {
mButtonSendPressedCallback = onButtonSendPressedCallback;
}
public SurveyPagerAdapter(List<RecyclerView> views, List<Page> pages, Context context,
AppCompatActivity activity, ViewPager viewPager, Location location,
onSaveCallback onSaveCallback, boolean hasAnswers, String clientCode) {
mViews = views;
mPages = pages;
mContext = context;
mActivity = activity;
this.viewPager = viewPager;
requiredQuestions = new ArrayList<>();
manager = SettingsManager.getInstance(mContext);
this.location = location;
this.onSaveCallback = onSaveCallback;
this.hasAnswers = hasAnswers;
this.clientCode = clientCode;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
private String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public View getView(int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mPages.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
final ConstraintLayout view = (ConstraintLayout) LayoutInflater.from(container.getContext()).inflate(R.layout.survey_container, container, false);
final RecyclerView recyclerView = view.findViewById(R.id.my_recycler_view);
final Button buttonNext = view.findViewById(R.id.button_next);
final Button buttonPrev = view.findViewById(R.id.button_prev);
for (Questions question : mPages.get(position).getQuestions()) {
if (question.isRequired()) {
requiredQuestions.add(question.getId());
}
}
buttonPrev.setVisibility(View.GONE);
SurveyPagerListAdapter detailsAdapter = new SurveyPagerListAdapter(mContext, mActivity,
mPages.get(position).getQuestions(), hasAnswers, getAnswersList(),
clientCode);
// Create recycler view for each page
recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
recyclerView.setAdapter(detailsAdapter);
recyclerView.setNestedScrollingEnabled(true);
// Manage previous and next buttons
liveData.observe(mActivity, index -> {
if (!hasAnswers) {
if (mPages.size() > 1) {
if (position == 0) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
} else if (position == getCount() - 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.send_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
} else if (mPages.size() == 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.send_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
} else {
buttonPrev.setVisibility(View.GONE);
}
} else {
if (mPages.size() > 0) {
if (position == 0) {
if (mPages.size() == 1) {
buttonPrev.setVisibility(View.GONE);
buttonNext.setVisibility(View.GONE);
} else {
buttonPrev.setVisibility(View.GONE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
} else if (position == getCount() - 1) {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setVisibility(View.GONE);
} else {
buttonPrev.setVisibility(View.VISIBLE);
buttonNext.setText(mContext.getString(R.string.next_survey));
buttonNext.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_baseline_arrow_forward_ios_24, 0);
}
}
}
});
final ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
liveData.postValue(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
viewPager.setOnPageChangeListener(onPageChangeListener);
onPageChangeListener.onPageSelected(viewPager.getCurrentItem());
buttonNext.setOnClickListener(onNextClickListener);
buttonPrev.setOnClickListener(onBackClickListener);
container.addView(view);
headerId = mPages.get(position).getHeaderId();
return view;
}
private void processSendingSurvey() {
SurveyListHeader surveyListHeaderDb = new SurveyListHeader();
Date currentDate = new Date();
String closedDate = new SimpleDateFormat(SoapApi.SEND_DATE_FORMAT_Z, Locale.getDefault()).format(currentDate);
ArrayList<SurveyListHeader> surveyListDB = SurveyListHeader.selectAllSingle(Utils.getDb(mContext));
for (SurveyListHeader header : surveyListDB) {
if (header.getCode().equals(getCode())) {
surveyListHeaderDb.setCode(getCode());
surveyListHeaderDb.setCustomerCode(header.getCustomerCode());
surveyListHeaderDb.setCustomerType(header.getCustomerType());
surveyListHeaderDb.setOpenDate(header.getOpenDate());
surveyListHeaderDb.setOpenLatitude(header.getOpenLatitude());
surveyListHeaderDb.setOpenLongitude(header.getOpenLongitude());
surveyListHeaderDb.setClosedDate(closedDate);
surveyListHeaderDb.setClosedLatitude(String.valueOf(location.getLongitude()));
surveyListHeaderDb.setClosedLongitude(String.valueOf(location.getLatitude()));
ArrayList<SurveyListLines> surveyLinesList = SurveyListLines.selectAll(Utils.getDb(mContext), questionId);
surveyListHeaderDb.setSurveyLines(surveyLinesList);
// if (surveyLinesList.size() > 0) {
ArrayList<SurveyListHeader> newList = new ArrayList<>();
newList.add(surveyListHeaderDb);
if (!Utils.isNetworkConnected(mContext)) {
if (closedDate.equals("-1")) {
surveyListHeaderDb.save(Utils.getDb(mContext));
}
} else {
sendRequest(newList);
}
// } else {
// Toast.makeText(mContext, mContext.getString(R.string.no_question_answered), Toast.LENGTH_SHORT).show();
// }
}
}
}
private void sendRequest(ArrayList<SurveyListHeader> surveyList) {
SurveyRequestAnswers requestAnswers = new SurveyRequestAnswers();
String userId = manager.getUserID();
String catalog = manager.getCatalog();
String username = manager.getUsername();
String userDescription = manager.getUserDesc();
String deviceId = manager.getDeviceId();
String lang = manager.getLanguage();
String versionNo = Utils.getVersionNo(mContext);
al.logic.android.webflex.survey.models.answers.UserData userData = new al.logic.android.webflex.survey.models.answers.UserData();
userData.setCatalog(catalog);
userData.setUserId(userId);
userData.setUserDescription(userDescription);
userData.setDeviceId(deviceId);
userData.setLang(lang);
userData.setUserName(username);
userData.setVersionNo(versionNo);
requestAnswers.setUserData(userData);
requestAnswers.setSurveyHeader(surveyList);
onSaveCallback.onSave(requestAnswers);
}
private final View.OnClickListener onNextClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!hasAnswers && viewPager.getCurrentItem() == getCount() - 1) {
mButtonSendPressedCallback.isPressed(true);
processSendingSurvey();
} else {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
mButtonSendPressedCallback.isPressed(true);
}
}
};
private final View.OnClickListener onBackClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
}
};
public List<RecyclerView> getViews() {
return mViews;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mPages.get(position).getDescription();
}
public interface onSaveCallback {
void onSave(SurveyRequestAnswers requestAnswers);
}
public interface OnButtonSendPressedCallback {
void isPressed(boolean isPressed);
}
}
And them my adapter is:
public class SurveyPagerListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final List<Questions> questions;
private final Context mContext;
private final AppCompatActivity mActivity;
private final boolean hasAnswers;
private final String clientCode;
private final List<Answers> answersList;
public SurveyPagerListAdapter(Context context, AppCompatActivity activity, List<Questions> questions,
boolean hasAnswers,
List<Answers> answersList, String clientCode) {
mContext = context;
mActivity = activity;
this.questions = questions;
this.hasAnswers = hasAnswers;
this.answersList = answersList;
this.clientCode = clientCode;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == R.layout.layout_survey_radio_buttons) {
view = inflater.inflate(R.layout.layout_survey_radio_buttons, parent, false);
return new RadioButtonsViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_checkboxes) {
view = inflater.inflate(R.layout.layout_survey_checkboxes, parent, false);
return new CheckboxesViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_dropdown) {
view = inflater.inflate(R.layout.layout_survey_dropdown, parent, false);
return new SpinnerViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_date) {
view = inflater.inflate(R.layout.layout_survey_date, parent, false);
return new DateViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_choose_file) {
view = inflater.inflate(R.layout.layout_survey_choose_file, parent, false);
return new ChoosePhotoViewHolder(view, mContext, mActivity, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_rating_stars) {
view = inflater.inflate(R.layout.layout_survey_rating_stars, parent, false);
return new RatingStarsViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_rating_numbers) {
view = inflater.inflate(R.layout.layout_survey_rating_numbers, parent, false);
return new RatingNumberViewHolder(view, mContext, hasAnswers, clientCode);
} else if (viewType == R.layout.layout_survey_input) {
view = inflater.inflate(R.layout.layout_survey_input, parent, false);
return new EditTextViewHolder(view, mContext, hasAnswers, clientCode);
} else {
return null;
}
}
#Override
public int getItemViewType(int position) {
if (isRadioButton(position)) {
return R.layout.layout_survey_radio_buttons;
} else if (isCheckBox(position)) {
return R.layout.layout_survey_checkboxes;
} else if (isSpinner(position)) {
return R.layout.layout_survey_dropdown;
} else if (isDate(position)) {
return R.layout.layout_survey_date;
} else if (isChoosePhoto(position)) {
return R.layout.layout_survey_choose_file;
} else if (isRatingStars(position)) {
return R.layout.layout_survey_rating_stars;
} else if (isRatingNumbers(position)) {
return R.layout.layout_survey_rating_numbers;
} else if (isEditText(position)) {
return R.layout.layout_survey_input;
} else if (isString(position)) {
return R.layout.layout_survey_input;
} else {
return -1;
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final Questions question = questions.get(position);
if (holder.getItemViewType() == R.layout.layout_survey_radio_buttons) {
if (holder instanceof RadioButtonsViewHolder) {
((RadioButtonsViewHolder) holder).bind(question);
((RadioButtonsViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_checkboxes) {
if (holder instanceof CheckboxesViewHolder) {
((CheckboxesViewHolder) holder).bind(question);
((CheckboxesViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_dropdown) {
if (holder instanceof SpinnerViewHolder) {
((SpinnerViewHolder) holder).bind(question);
((SpinnerViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_date) {
if (holder instanceof DateViewHolder) {
((DateViewHolder) holder).bind(question);
((DateViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_choose_file) {
if (holder instanceof ChoosePhotoViewHolder) {
((ChoosePhotoViewHolder) holder).bind(question);
((ChoosePhotoViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_rating_stars) {
if (holder instanceof RatingStarsViewHolder) {
((RatingStarsViewHolder) holder).bind(question);
((RatingStarsViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_rating_numbers) {
if (holder instanceof RatingNumberViewHolder) {
((RatingNumberViewHolder) holder).bind(question);
((RatingNumberViewHolder) holder).bindAnswers(answersList);
}
} else if (holder.getItemViewType() == R.layout.layout_survey_input) {
if (holder instanceof EditTextViewHolder) {
((EditTextViewHolder) holder).bind(question);
((EditTextViewHolder) holder).bindAnswers(answersList);
}
}
}
#Override
public int getItemCount() {
return questions == null ? 0 : questions.size();
}
private boolean isRadioButton(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_RADIO);
}
private boolean isCheckBox(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_CHECKBOX);
}
private boolean isSpinner(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_DROPDOWN);
}
private boolean isDate(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_DATE);
}
private boolean isChoosePhoto(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_IMAGE);
}
private boolean isRatingStars(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_STAR);
}
private boolean isRatingNumbers(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_NUMBER);
}
private boolean isEditText(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_TEXT_BOX);
}
private boolean isString(int position) {
return questions.get(position).getType().toLowerCase(Locale.ROOT).equals(SurveyConstants.TYPE_STRING);
}
}
and for example the Radio Button viewholder:
public class RadioButtonsViewHolder extends BaseViewHolder {
private final ImageView tooltipHelpButton;
private final TextView questionDescription;
private final TextInputLayout textViewComment;
private final RadioGroup radioGroup;
private final ImageView imageRequired;
private final TextInputEditText editTextComment;
private final EditText editTextOther;
private final Context mContext;
private final AppCompatActivity mActivity;
int questionId;
private final boolean hasAnswers;
private final String clientCode;
private int checkedRadioButtonId;
private int headerId;
public RadioButtonsViewHolder(#NonNull View itemView, Context context,
AppCompatActivity activity, boolean hasAnswers, String clientCode) {
super(itemView);
mContext = context;
mActivity = activity;
this.hasAnswers = hasAnswers;
this.clientCode = clientCode;
tooltipHelpButton = itemView.findViewById(R.id.tooltip_button);
questionDescription = itemView.findViewById(R.id.question_description);
radioGroup = itemView.findViewById(R.id.question_radio_group);
editTextOther = itemView.findViewById(R.id.question_radioButton_other);
imageRequired = itemView.findViewById(R.id.image_required);
textViewComment = itemView.findViewById(R.id.textView_question_comment);
editTextComment = itemView.findViewById(R.id.edittext_question_comment);
if (hasAnswers) {
editTextComment.setFocusable(false);
editTextComment.setEnabled(false);
editTextOther.setFocusable(false);
editTextOther.setEnabled(false);
tooltipHelpButton.setVisibility(View.GONE);
}
}
#Override
public void bind(Questions question) {
questionId = question.getId();
headerId = question.getHeaderId();
questionDescription.setText(question.getRank() + "." + question.getDescription());
if (question.isRequired()) {
imageRequired.setVisibility(View.VISIBLE);
}
if (question.isShowComment()) {
textViewComment.setVisibility(View.VISIBLE);
}
if (question.getHelpInfo().length() != 0 && !hasAnswers) {
tooltipHelpButton.setVisibility(View.VISIBLE);
TooltipCompat.setTooltipText(tooltipHelpButton, question.getHelpInfo());
questionDescription.setOnLongClickListener(view -> {
TooltipCompat.setTooltipText(questionDescription, question.getHelpInfo());
return false;
});
}
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
// Create radio buttons
radioGroup.removeAllViews();
int lastItem = -1;
for (Options option : question.getOptions()) {
RadioButton radioButton = new RadioButton(mContext);
radioButton.setText(option.getText());
radioButton.setId(option.getId());
setRadioButtonStyle(radioButton);
radioGroup.addView(radioButton, params);
if (hasAnswers) {
radioButton.setEnabled(false);
}
lastItem = radioGroup.getChildCount() - 1;
if (!hasAnswers) {
editTextComment.clearFocus();
Utils.hideKeyboardFrom(mContext, editTextComment);
int finalLastItem = lastItem;
radioGroup.setOnCheckedChangeListener((radioGroup, checkedId) -> {
if (radioButton.isChecked() && checkedId == radioGroup.getChildAt(finalLastItem).getId()) {
editTextOther.setVisibility(View.VISIBLE);
if (checkedId == radioGroup.getChildAt(finalLastItem).getId()) {
editTextOther.setVisibility(View.VISIBLE);
}
} else {
editTextOther.setVisibility(View.GONE);
}
checkedRadioButtonId = checkedId;
});
}
}
if (question.isShowOther() && !hasAnswers) {
radioGroup.getChildAt(lastItem).setVisibility(View.VISIBLE);
} else if (!question.isShowOther() && !hasAnswers) {
radioGroup.getChildAt(lastItem).setVisibility(View.GONE);
}
if (!hasAnswers) {
List<SurveyListHeader> headers = SurveyListHeader.selectAll(Utils.getDb(mContext), clientCode);
for (SurveyListHeader header : headers) {
String closedDate = header.getClosedDate();
ArrayList<SurveyListLines> surveyListLines = SurveyListLines.selectAll(Utils.getDb(mContext), headerId);
for (SurveyListLines surveyLine : surveyListLines) {
if (closedDate.equals("-1")) {
if (surveyLine.getQuestionId() == question.getId()) {
editTextComment.setText(surveyLine.getComments());
radioGroup.check(surveyLine.getOptionId());
questionDescription.setText(question.getRank() + "." + question.getDescription());
editTextOther.setText(surveyLine.getOther());
}
}
}
}
}
itemView.setOnClickListener(view -> {
editTextComment.clearFocus();
Utils.hideKeyboardFrom(mContext, editTextComment);
});
}
#Override
public void bindAnswers(List<Answers> answers) {
if (hasAnswers) {
if (answers != null) {
for (Answers currentAnswer : answers) {
for (AnswerLines currentLine : currentAnswer.getAnswerLines()) {
if (currentLine.getQuestionId() == questionId) {
radioGroup.check(currentLine.getOptionId());
if (!(currentLine.getComments() != null && currentLine.getComments().equals(""))) {
editTextComment.setVisibility(View.VISIBLE);
editTextComment.setText(currentLine.getComments());
} else {
editTextComment.setVisibility(View.GONE);
}
if (!(currentLine.getOther() != null && currentLine.getOther().equals(""))) {
editTextOther.setVisibility(View.VISIBLE);
editTextOther.setText(currentLine.getOther());
} else {
editTextOther.setVisibility(View.GONE);
RadioButton otherRadioButton = (RadioButton) radioGroup.getChildAt(radioGroup.getChildCount() - 1);
otherRadioButton.setVisibility(View.GONE);
}
}
}
}
}
}
}
public void setRadioButtonStyle(RadioButton radioButton) {
radioButton.setButtonDrawable(R.drawable.radiobutton_selector);
radioButton.setPadding(16, 16, 16, 16);
radioButton.setTextColor(ContextCompat.getColor(mContext, R.color.gray_medium));
}
#Override
public void isPressed(boolean isPressed) {
if (isPressed) {
SurveyListLines surveyLine = new SurveyListLines();
surveyLine.setQuestionId(questionId);
surveyLine.setOptionId(checkedRadioButtonId);
surveyLine.setComments(Objects.requireNonNull(editTextComment.getText()).toString());
surveyLine.setHeaderId(headerId);
surveyLine.setOther(Objects.requireNonNull(editTextOther.getText().toString()));
surveyLine.save(Utils.getDb(mContext));
}
}
}
I'm looking to find a right way how to implement the survey, I'm doing some research which of design patterns can fit for this kind of application. The only problem is to manage the send button from ViewPager, the user interface is fine. If anyone have some suggestions about this I would be glad to hear.
Thanks in advance.

Can't pass null for argument 'pathString' in child() in my (MessagesAdapter.java:114)

I receive this error when I run my application. It was run without error but when I open my app and react feeling on my msg then application suddenly stop working and show this error ( Can't pass null for argument 'pathString' in child() )
Here is my code:
public class MessagesAdapter extends RecyclerView.Adapter{
Context context;
ArrayList<Message> messages;
final int ITEM_SENT = 1;
final int ITEM_RECEIVE = 2;
String senderRoom;
String receiverRoom;
public MessagesAdapter (Context context, ArrayList<Message>messages, String senderRoom, String receiverRoom){
this.context = context;
this.messages = messages;
this.senderRoom = senderRoom;
this.receiverRoom = receiverRoom;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == ITEM_SENT){
View view = LayoutInflater.from(context).inflate(R.layout.item_send, parent, false);
return new SentViewHolder(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.item_receive, parent, false);
return new ReceiverViewHolder(view);
}
}
#Override
public int getItemViewType(int position) {
Message message = messages.get(position);
if (FirebaseAuth.getInstance().getUid().equals(message.getSenderId())){
return ITEM_SENT;
} else {
return ITEM_RECEIVE;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Message message = messages .get(position);
int reactions[] = new int[]{
R.drawable.like,
R.drawable.heart,
R.drawable.smile,
R.drawable.laughing,
R.drawable.surprised,
R.drawable.sad,
R.drawable.angry,
};
ReactionsConfig config = new ReactionsConfigBuilder(context)
.withReactions(reactions)
.build();
ReactionPopup popup = new ReactionPopup(context, config, (pos) -> {
if (holder.getClass() == SentViewHolder.class) {
SentViewHolder viewHolder = (SentViewHolder)holder;
viewHolder.binding.feeling.setImageResource(reactions[pos]);
viewHolder.binding.feeling.setVisibility(View.VISIBLE);
} else {
ReceiverViewHolder viewHolder = (ReceiverViewHolder) holder;
viewHolder.binding.feeling.setImageResource(reactions[pos]);
viewHolder.binding.feeling.setVisibility(View.VISIBLE);
}
message.setFeeling(pos);
FirebaseDatabase.getInstance().getReference()
.child("chats")
.child(senderRoom) HERE I RECEIVED ERROR
.child("messages")
.child(message.getMessageId()).setValue(message);
FirebaseDatabase.getInstance().getReference()
.child("chats")
.child(receiverRoom)
.child("messages")
.child(message.getMessageId()).setValue(message);
return true; // true is closing popup, false is requesting a new selection
});
if (holder.getClass() == SentViewHolder.class) {
SentViewHolder viewHolder = (SentViewHolder) holder;
viewHolder.binding.message.setText(message.getMessage());
if (message.getFeeling() >= 0) {
message.setFeeling(reactions[(int) message.getFeeling()]);
viewHolder.binding.feeling.setVisibility(View.VISIBLE);
} else {
viewHolder.binding.feeling.setVisibility(View.GONE);
}
viewHolder.binding.message.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popup.onTouch(v, event);
return false;
}
});
} else {
ReceiverViewHolder viewHolder = (ReceiverViewHolder) holder;
viewHolder.binding.message.setText(message.getMessage());
if (message.getFeeling() >= 0) {
message.setFeeling(reactions[(int) message.getFeeling()]);
viewHolder.binding.feeling.setVisibility(View.VISIBLE);
} else {
viewHolder.binding.feeling.setVisibility(View.GONE);
}
viewHolder.binding.message.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
popup.onTouch(v, event);
return false;
}
});
}
}
#Override
public int getItemCount() {
return messages.size();
}
public class SentViewHolder extends RecyclerView.ViewHolder {
ItemSendBinding binding;
public SentViewHolder(#NonNull View itemView) {
super(itemView);
binding = ItemSendBinding.bind(itemView);
}
}
public class ReceiverViewHolder extends RecyclerView.ViewHolder{
ItemReceiveBinding binding;
public ReceiverViewHolder(#NonNull View itemView) {
super(itemView);
binding = ItemReceiveBinding.bind(itemView);
}
}
}

How to get data from nested Recycler View having CheckBox?

Actually this screen displays a set of questions and the task is to read the user entered or selected answer.
So the my question is, how to get the value from ChooseAdapter to QuestionAdapter and then get all the value from QuestionAdapter to my Activity.
My english is little bit weak, sorry for that.
And thanks in advance.
Main adapter : QuestionAdapter.java
public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.RecyclerViewHolder> {
private ArrayList<Question> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = QuestionsAdapter.class.getSimpleName();
private static Context mContext;
private NetworkManager nm;
private boolean visibility = false;
private ChoiceAdapter adapter;
private ArrayList<QuestionsAnswer> questionsAnswers = new ArrayList<>();
ArrayList<ChoiceAnswer> choiceAnswers;
public QuestionsAdapter(Context context, ArrayList<Question> recyclerViewItems) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Question data = (Question) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.txtQuestion.setText(data.getQuestion());
recyclerViewHolder.txtQuestionType.setText(data.getQuestionType());
if (data.getQuestionType().equals("MULT")) {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.VISIBLE);
recyclerViewHolder.edtQuestion.setVisibility(View.GONE);
if (data.getChoices().size() > 0) {
adapter = new ChoiceAdapter(mContext, data.getChoices(), position);
recyclerViewHolder.mRecyclerChoice.setAdapter(adapter);
}
} else {
recyclerViewHolder.mRecyclerChoice.setVisibility(View.GONE);
recyclerViewHolder.edtQuestion.setVisibility(View.VISIBLE);
}
recyclerViewHolder.btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (data.getQuestionType().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + recyclerViewHolder.edtQuestion.getText().toString());
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView txtQuestion,txtQuestionType;
EditText edtQuestion;
RecyclerView mRecyclerChoice;
Button btnOk;
private LinearLayoutManager linearLayoutManager;
public RecyclerViewHolder(View view) {
super(view);
txtQuestion = view.findViewById(R.id.txt_question);
edtQuestion = view.findViewById(R.id.edt_question);
mRecyclerChoice = view.findViewById(R.id.recycler_choice);
btnOk = view.findViewById(R.id.btn_ok);
txtQuestionType = view.findViewById(R.id.txt_question_type);
initRecyclerView();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtQuestionType.getText().toString().equals("MULT")) {
Log.v(TAG, "array Data : " + adapter.getChoiceAnswer());
} else {
Log.v(TAG, "array Data : " + edtQuestion.getText().toString());
}
}
});
}
private void initRecyclerView() {
//setting properties of recyclerView
mRecyclerChoice.setHasFixedSize(true);
mRecyclerChoice.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(mContext);
mRecyclerChoice.setLayoutManager(linearLayoutManager);
}
}
public static void validation() {
Toast.makeText(mContext, "testing", Toast.LENGTH_SHORT).show();
}}
for list of CheckBox : ChooseAdapter.java
public class ChoiceAdapter extends RecyclerView.Adapter<ChoiceAdapter.RecyclerViewHolder> {
private ArrayList<Choice> mRecyclerViewItems;
private static final int MENU_ITEM_VIEW_TYPE = 0;
private static final String TAG = ChoiceAdapter.class.getSimpleName();
private Context mContext;
private NetworkManager nm;
// private OnItemClickListener mOnItemClickListener;
private boolean visibility = false;
private static ArrayList<ChoiceAnswer> choiceAnswerArrayList;
private ChoiceAnswer choiceAnswer;
String arrayData;
public ChoiceAdapter(Context context, ArrayList<Choice> recyclerViewItems, int position) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
// choiceAnswer.key = 0;
choiceAnswerArrayList = new ArrayList<>();
//initializing choiceAnswer
choiceAnswer = new ChoiceAnswer();
choiceAnswer.values = new ArrayList<>();
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//this view contains recycler view under recycler view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio_button, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(v);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
default:
final RecyclerViewHolder recyclerViewHolder = (RecyclerViewHolder) holder;
Choice data = (Choice) mRecyclerViewItems.get(position);
try {
recyclerViewHolder.checkChoice.setText(data.getChoiceName());
recyclerViewHolder.checkChoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
arrayData = "";
for (int i = 0; i < mRecyclerViewItems.size(); i++) {
if (isChecked) {
if (!choiceAnswer.values.contains(data.getChoiceID())) {
choiceAnswer.values.add(i, data.getChoiceID());
}
} else {
choiceAnswer.values.remove(data.getChoiceID());
// arrayData = choiceAnswer.values.toString().replace("[", "").replace("]", "").trim();
}
try {
arrayData = arrayData + "," + choiceAnswer.values.get(i);
}catch (IndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
public String getChoiceAnswer() {
return arrayData;
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
class RecyclerViewHolder extends RecyclerView.ViewHolder {
CheckBox checkChoice;
public RecyclerViewHolder(View view) {
super(view);
checkChoice = view.findViewById(R.id.check_choice);
}
}}
Please help me guys I am trying this since last 3 days...
I've implemented my own login too, but it didn't working properly.

How can I change the colour of recyclerView item on button pressed?

I have a fragment containing a recyclerView.
When a user presses on one of their recorded exercise sets, the particular set is highlighted green.
Basically this allows them to update the weight/ reps for that particular set if they want to.
When a user then decides to press the update button, I will run a SQL query to update the weight/ reps as they entered, however I also need to deselect the selected set (recyclerView item).
I need the colour to return back to dark grey. How could this be achieved?
Fragment (Relative Code)
#Override
public void onExerciseClicked(int position) {
if (recyclerItemClicked == false) {
saveBtn.setText("Update");
clearBtn.setVisibility(View.GONE);
recyclerItemClicked = true;
double selectedWeight = adapter.getWeight(position);
String selectedWeightString = Double.toString(selectedWeight);
editTextWeight.setText(selectedWeightString);
int selectedReps = adapter.getReps(position);
String selectedRepsString = Integer.toString(selectedReps);
editTextReps.setText(selectedRepsString);
} else {
clearBtn.setVisibility(View.VISIBLE);
saveBtn.setText("Save");
recyclerItemClicked = false;
}
}
public void initRecyclerView() {
adapter = new CompletedExercisesListAdapter2(allExercises, this);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
}
Adapter
public class CompletedExercisesListAdapter2 extends RecyclerView.Adapter {
private OnExerciseClickListener onExerciseClickListener;
private List<Log_Entries> allCompletedExercises = new ArrayList<>();
public int adapterPos = -1;
public boolean isSelected = false;
public boolean swipeDetected = false;
public CompletedExercisesListAdapter2(ArrayList<Log_Entries> allCompletedExercises, OnExerciseClickListener onExerciseClickListener) {
this.allCompletedExercises = allCompletedExercises;
this.onExerciseClickListener = onExerciseClickListener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == 0) {
view = layoutInflater.inflate(R.layout.new_completed_exercise_item, parent, false);
return new ViewHolderOne(view, onExerciseClickListener);
}
view = layoutInflater.inflate(R.layout.completed_exercise_item, parent, false);
return new ViewHolderTwo(view, onExerciseClickListener);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == 0) {
ViewHolderOne viewHolderOne = (ViewHolderOne) holder;
Log.d("adapterPos", String.valueOf(adapterPos));
Log.d("position", String.valueOf(position));
if (adapterPos == position) {
viewHolderOne.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderOne.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderOne.textViewExerciseName.setText(String.valueOf(allCompletedExercises.get(position).getChildExerciseName()));
viewHolderOne.textViewSetNumber.setText(String.valueOf(viewHolderOne.getAdapterPosition() + 1));
viewHolderOne.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderOne.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
} else if (getItemViewType(position) == 1) {
ViewHolderTwo viewHolderTwo = (ViewHolderTwo) holder;
if (adapterPos == position) {
viewHolderTwo.relativeLayout.setBackgroundColor(Color.parseColor("#567845"));
} else {
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
if(adapterPos >-1 && swipeDetected == true){
viewHolderTwo.relativeLayout.setBackgroundResource(R.color.dark_grey);
}
viewHolderTwo.textViewSetNumber.setText(String.valueOf(viewHolderTwo.getAdapterPosition() + 1));
viewHolderTwo.textViewWeight.setText(String.valueOf(allCompletedExercises.get(position).getTotal_weight_lifted()));
viewHolderTwo.textViewReps.setText(String.valueOf(allCompletedExercises.get(position).getReps()));
}
}
#Override
public int getItemCount() {
return allCompletedExercises.size();
}
#Override
public int getItemViewType(int position) {
// if list is sorted chronologically
if (position == 0) {
return 0;
}
if (allCompletedExercises.get(position).getChildExerciseName().equals(allCompletedExercises.get(position - 1).getChildExerciseName())) {
return 1;
} else {
return 0;
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewExerciseName;
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderOne(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewExerciseName = itemView.findViewById(R.id.textView_ExerciseName3);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number56);
textViewWeight = itemView.findViewById(R.id.textView_weight78);
textViewReps = itemView.findViewById(R.id.textView_repss0);
mOnExerciseClickListener = onExerciseClickListener;
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_relative);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (isSelected) {
adapterPos = -1;
isSelected = false;
} else {
adapterPos = getAdapterPosition();
isSelected = true;
}
notifyDataSetChanged();
}
}
class ViewHolderTwo extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewSetNumber;
private TextView textViewWeight;
private TextView textViewReps;
OnExerciseClickListener mOnExerciseClickListener;
private RelativeLayout relativeLayout;
public ViewHolderTwo(#NonNull View itemView, OnExerciseClickListener onExerciseClickListener) {
super(itemView);
textViewSetNumber = itemView.findViewById(R.id.textView_Set_Number);
textViewWeight = itemView.findViewById(R.id.textView_weight);
textViewReps = itemView.findViewById(R.id.textView_repss);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.exercise_item_rel);
mOnExerciseClickListener = onExerciseClickListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExerciseClickListener.onExerciseClicked(getAdapterPosition());
if (!isSelected) {
adapterPos = getAdapterPosition();
isSelected = true;
} else {
adapterPos = -1;
isSelected = false;
}
notifyDataSetChanged();
}
}
public interface OnExerciseClickListener {
void onExerciseClicked(int position);
}
}
}
Create a separate method in your adapter for clearing the selection.
public void clearSelection() {
adapterPos = -1;
isSelected = false;
notifyDataSetChanged();
}
Then call adapter.clearSelection() from your update click listener.

recyclerview.onBindviewholder always in position 0

recyclerview.onbindviewholder always in position 0
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {
public static final int UNCOMPLETED = 0;
public static final int COMPLETED = 1;
public static final int HIGHTLIGHT = 2;
public static final int HIGHTLIGHT_COMPETED = 3;
Cursor cursor;
Context context;
public NoteAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
public Cursor getCursor() {
return this.cursor;
}
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
public int getItemViewType(int position) {
if (cursor.moveToPosition(position)) {
cursor.move(position);
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
int hightlight = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_HIGHTLIGHT));
if (completed == 1) {
if (hightlight == 1) {
return HIGHTLIGHT_COMPETED;
}
return COMPLETED;
}
if (hightlight == 1 && completed == 0) {
return HIGHTLIGHT;
}
return UNCOMPLETED;
}
return -1;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_row, parent, false);
switch (viewType) {
case UNCOMPLETED:
view = inflater.inflate(R.layout.item_row, parent, false);
break;
case COMPLETED:
view = inflater.inflate(R.layout.item_row_completed, parent, false);
break;
case HIGHTLIGHT:
view = inflater.inflate(R.layout.item_row_hightlight, parent, false);
break;
case HIGHTLIGHT_COMPETED:
view = inflater.inflate(R.layout.item_row_hightlight_completed, parent, false);
break;
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
if (!cursor.moveToPosition(position)) {
return;
}
String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT));
Date date = Utilities.stringToDate(cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_DEADLINE)));
int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED));
holder.tvContent.setText(content);
holder.tvDate.setText(Utilities.dateToString(date));
if(completed == 1){
holder.imgIcon.performClick();
}
}
#Override
public int getItemCount() {
return (cursor.getCount());
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvContent;
TextView tvDate;
ImageButton imgIcon;
public ViewHolder(#NonNull final View itemView) {
super(itemView);
tvContent = itemView.findViewById(R.id.tvContent);
tvDate = itemView.findViewById(R.id.tvDate);
imgIcon = itemView.findViewById(R.id.imgCheck);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
cursor.move(position);
Note note = Utilities.cursorToNote(cursor);
Intent intent = new Intent(itemView.getContext(), AddNoteActivity.class);
intent.putExtras(note.sendNoteBundle());
intent.putExtra("type", true);
itemView.getContext().startActivity(intent);
}
});
}
}
}
The program does not contain any errors.
When I run the program, it always only shows the element at the 0 position, the remaining positions do not show.
function getItemCount works normally, returning 20 elements.
English is not my native language, sorry for any grammatical errors. Thanks, everyone.
Make sure the android:layout_height for your parent layout in the layout(xml) files for the various ViewHolders has been set to wrap_content instead of match_parent.

Categories

Resources