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.
Related
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.
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.
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;
}
So first I initialized my listview and added registerForContextMenu(my_list)
chatLists = (ListView)findViewById(R.id.chatlist);
chatLists.setAdapter(new ContactListAdapter(this));
registerForContextMenu(chatLists);
Then I added the OnCreateContextMenu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.chatlist) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_context, menu);
}
}
But After running the app.. When I long press on any list items, it's not showing any context Menu..
here is some sample code u can use:
`
... onCreateView{
.....
notiList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
setListMultiSelectListener();
}
public void setListMultiSelectListener() {
notiList.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// clear your list selection here
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(final ActionMode mode, Menu menu) {
// inflate your action menu here
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.delete_mode_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_select_all:
if (mAdapter.isAllSelected()) {
mAdapter.clearSelection();
for (int i = 0; i < notiList.getAdapter().getCount(); i++) {
notiList.setItemChecked(i, false);
}
} else {
mAdapter.selectAllItems();
for (int i = 0; i < notiList.getAdapter().getCount(); i++) {
notiList.setItemChecked(i, true);
}
}
break;
case R.id.action_delete:
mAdapter.deleteSelectedItems();
mode.finish();
break;
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
deletionMode = mode;
if (checked) {
nr = nr + 1;
mAdapter.setNewSelection(position, checked);
} else {
nr = nr - 1;
mAdapter.removeSelection(position);
}
if (mAdapter.isAllSelected()) {
mode.getMenu().findItem(R.id.action_select_all).setIcon(R.drawable.check);
} else {
mode.getMenu().findItem(R.id.action_select_all).setIcon(R.drawable.uncheck);
}
}
});
}
`
here is adapter:
public class NotificationListAdapter extends BaseAdapter {
private MainActivity context;
private Vector<MessageInboxBean> messagesList;
private DisplayImageOptions /* options, */ options1;
private ImageLoader imageLoader;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private NotiItemHolder holder;
private boolean isHomeworkTab;
private LineColorPicker colorPicker;
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
int msgTypeId;
public NotificationListAdapter(MainActivity context, int msgTypeId, Vector<MessageInboxBean> messagesList, DisplayImageOptions options, boolean isHomeworkTab) {
this.context = context;
this.messagesList = messagesList;
// this.options = options;
options1 = new DisplayImageOptions.Builder()//
.showImageOnLoading(R.drawable.default_teacher)//
.showImageForEmptyUri(R.drawable.default_teacher)//
.showImageOnFail(R.drawable.default_teacher)//
.cacheInMemory(true)//
.cacheOnDisk(true)//
.considerExifParams(true)//
.displayer(new RoundedBitmapDisplayer(0))//
.build();
this.isHomeworkTab = isHomeworkTab;
this.msgTypeId = msgTypeId;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
if (this.messagesList == null) {
messagesList = getMessagesList(this.msgTypeId);
}
// if (this.messagesList.size() == 0) {
// messagesList = getMessagesList(this.msgTypeId);
// }
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
public void selectAllItems() {
mSelection = new HashMap<Integer, Boolean>();
for (int i = 0; i < messagesList.size(); i++) {
mSelection.put(i, true);
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
if (mSelection.size() == messagesList.size()) {
return true;
} else {
return false;
}
}
public void deleteSelectedItems() {
ArrayList<Integer> notiIdAray = new ArrayList<Integer>();
for (int i = 0; i < messagesList.size(); i++) {
Boolean result = mSelection.get(i);
boolean result1 = result == null ? false : result;
if (result1) {
notiIdAray.add(messagesList.get(i).getNotificationId());
}
}
((MessageInboxTable) AppDb.getInstance(context).getTableObject(MessageInboxTable.TABLE_NAME)).deleteData(notiIdAray, context);
updateMessagesList(msgTypeId);
notifyDataSetChanged();
}
#Override
public int getCount() {
return messagesList.size();
}
#Override
public Object getItem(int position) {
return messagesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
#SuppressLint({ "NewApi", "InflateParams" })
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.notification_list_item, null);
holder = new NotiItemHolder();
holder.dueDate = (TextView) convertView.findViewById(R.id.dueDateTxt);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.day = (TextView) convertView.findViewById(R.id.day);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.message = (TextView) convertView.findViewById(R.id.message);
holder.subject = (TextView) convertView.findViewById(R.id.subject);
holder.doneStatus = (TextView) convertView.findViewById(R.id.doneStatus);
holder.sendersName = (TextView) convertView.findViewById(R.id.sendersName);
holder.notiDate = (TextView) convertView.findViewById(R.id.notiDate);
holder.sendersImg = (ImageView) convertView.findViewById(R.id.sendersImg);
holder.statusImg = (ImageView) convertView.findViewById(R.id.statusImg);
holder.star = (CheckBox) convertView.findViewById(R.id.star);
holder.doneLayout = (LinearLayout) convertView.findViewById(R.id.done_layout);
holder.endView = convertView.findViewById(R.id.endView);
convertView.setTag(holder);
} else {
holder = (NotiItemHolder) convertView.getTag();
}
MessageInboxBean bean = messagesList.get(position);
if (mSelection.get(position) != null) {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender_check);
holder.dueDate.setVisibility(View.INVISIBLE);
holder.date.setVisibility(View.INVISIBLE);
holder.day.setVisibility(View.INVISIBLE);
} else {
if (bean.getDueDate().trim().length() > 0) {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender);
holder.dueDate.setVisibility(View.VISIBLE);
holder.date.setVisibility(View.VISIBLE);
holder.day.setVisibility(View.VISIBLE);
holder.date.setText(getDueDate(bean.getDueDate()));
holder.day.setText(getDueDay(bean.getDueDate()));
} else {
convertView.findViewById(R.id.cal_img_layout).setBackgroundResource(R.drawable.calender_2);
holder.dueDate.setVisibility(View.INVISIBLE);
holder.date.setVisibility(View.INVISIBLE);
holder.day.setVisibility(View.INVISIBLE);
}
if (isHomeworkTab) {
holder.subject.setVisibility(View.VISIBLE);
holder.doneLayout.setVisibility(View.VISIBLE);
} else {
holder.subject.setVisibility(View.GONE);
holder.doneLayout.setVisibility(View.GONE);
}
}
holder.title.setText(bean.getTitle());
holder.message.setText(bean.getMessage());
if (isHomeworkTab) {
holder.subject.setText(getSubjectFromId(context, bean.getSubjectId()) == null ? "" : getSubjectFromId(context, bean.getSubjectId()));
String colr = getSubjectColorFromId(context, bean.getSubjectId());
if (colr != null) {
setColorToImage(holder.subject, 1, colr, false);
}
if (bean.getStatus().equals("0")) {
holder.doneStatus.setText("Not done");
holder.doneStatus.setTextColor(context.getResources().getColor(R.color.text_light_grey));
holder.statusImg.setImageResource(R.drawable.not_done);
} else {
holder.doneStatus.setText("Done");
holder.doneStatus.setTextColor(context.getResources().getColor(R.color.app_theme_color));
holder.statusImg.setImageResource(R.drawable.done);
}
}
holder.notiDate.setText(getMessageDate(bean.getMessageDate()));
if (bean.getStarred().equals("0")) {
holder.star.setChecked(false);
} else {
holder.star.setChecked(true);
}
holder.sendersName.setText("~" + bean.getSender());
// holder.notiDate
imageLoader.displayImage(bean.getSenderPicURL(), holder.sendersImg, options1, animateFirstListener);
holder.subject.setTag(position);
holder.star.setTag(position);
holder.doneLayout.setTag(position);
holder.subject.setOnClickListener(subjectClick);
holder.star.setOnCheckedChangeListener(starClick);
holder.doneLayout.setOnClickListener(doneClick);
if (position == getCount() - 1) {
holder.endView.setVisibility(View.VISIBLE);
} else {
holder.endView.setVisibility(View.GONE);
}
return convertView;
}
class NotiItemHolder {
TextView dueDate, date, day, title, message, subject, doneStatus, sendersName, notiDate;
ImageView sendersImg, statusImg;
CheckBox star;
LinearLayout doneLayout;
View endView;
}
}
I have RecycleView List with an ExpandableLinearLayout ( i use a third party library). In my ExpandableLinearLayout I have a ListView, with an custom ArrayAdapter.
I set my Adapter in the RecycleViewAdapter and submit one ArrayList that contains 4 ArrayLists and the position from the onBindViewHolder() method , too fill the different sections in the RecycleView.
I pass the data in the correct section but i get only the first element of each ArrayList. I Log some stuff and the problem is the position from the getView method in my ArrayAdapter is always 0..
I search and played around a bit but i didnt found a solution.. I hope somebody can help..
Sorry for my bad grammar
This is my RecycleView :
public class EmergencyPassAdapter extends RecyclerView.Adapter<EmergencyPassAdapter.EmergencyPassViewHolder> {
private static final String LOG_TAG = EmergencyPassAdapter.class.getName();
private Context context;
private ArrayList<CellInformation> cellInformations;
private SparseBooleanArray expandState = new SparseBooleanArray();
EmergencyPassExpandAdapter emergencyPassExpandAdapter;
public EmergencyPassAdapter(Context context, ArrayList<CellInformation> cellInformations) {
this.context = context;
this.cellInformations = cellInformations;
for (int i = 0; i < cellInformations.size(); i++) {
expandState.append(i, false);
}
}
#Override
public EmergencyPassViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_emergency_pass, parent, false);
return new EmergencyPassViewHolder(view);
}
#Override
public void onBindViewHolder(final EmergencyPassViewHolder holder, final int position) {
CellInformation cellInformation = cellInformations.get(position);
holder.imageViewIcon.setImageDrawable(cellInformation.getIcon());
holder.textViewTitle.setText(cellInformation.getTitel());
emergencyPassExpandAdapter = new EmergencyPassExpandAdapter(context, EmergencyPassExpandDetailFactory.getExpandCellInformation(context), position);
holder.listView.setAdapter(emergencyPassExpandAdapter);
if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_emergency_contacts))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else if (cellInformation.getTitel().equals(context.getResources().getString(R.string.emergency_informations_health_insurance_legal_guardian))) {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
} else {
holder.expandableLinearLayout.setExpanded(expandState.get(position));
holder.expandableLinearLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
expandState.put(position, true);
holder.imageViewArrow.setRotation(180);
}
#Override
public void onPreClose() {
expandState.put(position, false);
holder.imageViewArrow.setRotation(360);
}
});
}
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!holder.expandableLinearLayout.isExpanded()) {
Log.i(LOG_TAG, "expand");
holder.expandableLinearLayout.expand();
} else {
Log.i(LOG_TAG, "collapse");
holder.expandableLinearLayout.collapse();
}
}
});
}
#Override
public int getItemCount() {
return cellInformations.size();
}
public static class EmergencyPassViewHolder extends RecyclerView.ViewHolder {
TextView textViewTitle, textViewExpandText;
ImageView imageViewIcon, imageViewArrow;
ExpandableLinearLayout expandableLinearLayout;
RelativeLayout relativeLayout;
ListView listView;
public EmergencyPassViewHolder(View itemView) {
super(itemView);
textViewTitle = (TextView) itemView.findViewById(R.id.cell_emergency_pass_title_tv);
textViewExpandText = (TextView) itemView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
imageViewIcon = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_icon_iv);
imageViewArrow = (ImageView) itemView.findViewById(R.id.cell_emergency_pass_arrow_icon_iv);
expandableLinearLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.cell_emergency_pass_arrow_expandable_list);
relativeLayout = (RelativeLayout) itemView.findViewById(R.id.cell_emergency_pass_root_rl);
listView = (ListView) itemView.findViewById(R.id.cell_emergency_pass_expand_lv);
}
}
}
My ArrayAdapter
public class EmergencyPassExpandAdapter extends ArrayAdapter<CellExpandInformation>{
private static final String LOG_TAG = EmergencyPassExpandAdapter.class.getName();
private ArrayList<CellExpandInformation> values;
private int checkPosition;
private Context context;
public EmergencyPassExpandAdapter(Context context, ArrayList<CellExpandInformation> values, int checkPosition) {
super(context, -1, values);
this.context = context;
this.values = values;
this.checkPosition = checkPosition;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(LOG_TAG,"View");
Log.i(LOG_TAG,"Position: " + position);
EmergencyPassExpandViewHolder viewHolder;
CellExpandInformation cellExpandInformation = values.get(position);
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cell_emergency_pass_expand, parent, false);
viewHolder = new EmergencyPassExpandViewHolder();
viewHolder.textViewExpandTitle = (TextView) convertView.findViewById(R.id.cell_emergency_pass_expand_detail_tv);
convertView.setTag(viewHolder);
} else {
viewHolder = (EmergencyPassExpandViewHolder) convertView.getTag();
}
Log.i(LOG_TAG,"CheckPosition: " + checkPosition);
if (values != null) {
if (checkPosition == 0) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getMedications().get(position).getMedicationName());
Log.i(LOG_TAG, "Medications: " + cellExpandInformation.getMedications().get(position).getMedicationName());
} else if (checkPosition == 1) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getAllergies().get(position).getAllgergiesName());
} else if (checkPosition == 2) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getDiseases().get(position).getDiseasesName());
} else if (checkPosition == 3) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getLegalGuradian().get(position).getGuradianName());
} else if (checkPosition == 4) {
viewHolder.textViewExpandTitle.setText(cellExpandInformation.getEmergencyContact().get(position).getEmergencyContactName());
}
}
for(int i = 0; i < cellExpandInformation.getMedications().size(); i++){
Log.i(LOG_TAG,"Medis: " + cellExpandInformation.getMedications().get(i).getMedicationName());
}
return convertView;
}
static class EmergencyPassExpandViewHolder {
TextView textViewExpandTitle;
ImageView imageViewPhone, imageViewEmail, imageViewAdd;
}
}