firebase data being synced up in viewholder accidentally - java

I'm working on an app that is using an Expandable List Adapter to vote on certain characteristics of a movie. There's a problem where the viewholders are getting synced up with each other some, but not all of the time. i.e. the holder total and which button is clicked are changing together, despite the data in firebase. I'm trying to figure out how to keep the views separate.
I have a cloud function in firebase which does the math of converting a user vote to a movie vote and it is firing correctly.
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private DatabaseReference triggerDB;
private DatabaseReference userDB = FirebaseDatabase.getInstance().getReference("users");
private int userVote;
private int uv;
private Context mContext;
private ArrayList<Category> _listDataHeader; // header titles
private String imdbID;
private String title;
private String mUserId;
private ValueEventListener mUserListener;
private HashMap<DatabaseReference, ValueEventListener> hashMap = new HashMap<>();
public ExpandableListAdapter(Context context, String imdbID, String title, ArrayList<Category> listDataHeader) {
this.mContext = context;
this._listDataHeader = listDataHeader;
this.imdbID = imdbID;
this.title = title;
}
#Override
public Trigger getChild(int groupPosition, int childPosition) {
Category category = _listDataHeader.get(groupPosition);
ArrayList<Trigger> categoryArrayList = category.getTriggerList();
return categoryArrayList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
Category category = _listDataHeader.get(groupPosition);
ArrayList<Trigger> triggerList = category.getTriggerList();
return triggerList.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Category category = _listDataHeader.get(groupPosition);
String headerTitle = category.getCategoryName();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (infalInflater != null) {
convertView = infalInflater.inflate(R.layout.list_group, parent, false);
}
}
assert convertView != null;
TextView lblListHeader = convertView.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public void onGroupExpanded(int groupPosition) {
FirebaseDatabase.getInstance().goOnline();
super.onGroupExpanded(groupPosition);
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
removeValueEventListener(hashMap);
}
#Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
final ViewHolder holder;
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
DatabaseReference movieDB = FirebaseDatabase.getInstance().getReference("movies");
Category category = _listDataHeader.get(i);
ArrayList<Trigger> categoryArrayList = category.getTriggerList();
final Trigger trigger = categoryArrayList.get(i1);
final String tId = trigger.getId();
final String childText = trigger.getTriggerName();
triggerDB = movieDB.child(imdbID).child("Triggers").child(tId).child("votes");
if (view == null) {
view = LayoutInflater.from(mContext).inflate(R.layout.trigger_list_item, null);
holder = new ViewHolder();
holder.mTrigger = trigger;
setHolderData(view, holder, childText);
triggerDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("value").exists()) {
int value = dataSnapshot.child("value").getValue(Integer.class);
String valStr = String.valueOf(value);
holder.total.setText(valStr);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d("if", holder.mTrigger.getTriggerName());
view.setTag(holder);
}
else {
holder = (ViewHolder) view.getTag();
populateTriggerVote(holder, trigger, imdbID);
Log.d("else", holder.mTrigger.getTriggerName());
}
if (user != null) {
mUserId = user.getUid();
mUserListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
holder.myVote = dataSnapshot.getValue(int.class);
waitForVote(holder, i, mUserId, tId);
Log.d("PAXIE", String.valueOf(userVote));
if (holder.myVote == 0) {
holder.upButton.setChecked(false);
holder.downButton.setChecked(false);
}
if (holder.myVote == 1) {
//user has voted yuppers
holder.upButton.setChecked(true);
holder.downButton.setChecked(false);
}
if (holder.myVote == -1) {
//user has voted nopers
holder.upButton.setChecked(false);
holder.downButton.setChecked(true);
}
else {
Log.d("elsie", String.valueOf(holder.myVote));
}
}
else {
userDB.child(mUserId).child("changes").child(imdbID).child("triggers").child(trigger.getId()).setValue(0);
Log.d("Zippity","Doo Dah");
holder.myVote = 0;
Movie movie = new Movie(imdbID, title);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
}
else {
Log.d("Firing PEW PEW", "B");
}
userDB.child(mUserId).child("changes").child(imdbID).child("triggers").child(trigger.getId()).addValueEventListener(mUserListener);
hashMap.put(userDB, mUserListener);
return view;
}
private void setHolderData(View view, ViewHolder holder, String childText) {
holder.triggerName = view.findViewById(R.id.triggerName);
holder.upButton = view.findViewById(R.id.mTriggerButtonUp);
holder.downButton = view.findViewById(R.id.mTriggerButtonDown);
holder.total = view.findViewById(R.id.triggerCounter);
holder.triggerName.setText(childText);
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private void waitForVote(final ViewHolder holder, final int i, final String mUserId, final String tId) {
DatabaseReference movieDB = FirebaseDatabase.getInstance().getReference("movies");
triggerDB = movieDB.child(imdbID).child("Triggers").child(tId).child("votes");
holder.upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("trigger just voted on: ", (String) holder.triggerName.getText());
if ((holder.myVote == 0)||(holder.myVote == -1)) {
uv = 1;
}
else if (holder.myVote == 1) {
uv = 0;
}
else {
uv = 1;
}
holder.myVote = uv;
userDB.child(mUserId).child("changes").child(imdbID).child("triggers").child(holder.mTrigger.getId()).setValue(holder.myVote);
notifyDataSetChanged();
}
});
holder.downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("trigger just voted on: ", (String) holder.triggerName.getText());
if ((holder.myVote == 0)||(holder.myVote == 1)) {
uv = -1;
}
else if (holder.myVote == -1) {
uv = 0;
}
else {
uv = -1;
}
holder.myVote = uv;
userDB.child(mUserId).child("changes").child(imdbID).child("triggers").child(holder.mTrigger.getId()).setValue(holder.myVote);
notifyDataSetChanged();
// notifyDataSetChanged();
}
});
// notifyDataSetChanged();
}
private static class ViewHolder {
TextView triggerName;
ToggleButton upButton;
ToggleButton downButton;
TextView total;
int myVote;
Trigger mTrigger;
int voteTotal;
}
private static void removeValueEventListener(HashMap<DatabaseReference, ValueEventListener> hashMap) {
for (Map.Entry<DatabaseReference, ValueEventListener> entry : hashMap.entrySet()) {
DatabaseReference databaseReference = entry.getKey();
ValueEventListener valueEventListener = entry.getValue();
databaseReference.removeEventListener(valueEventListener);
Log.d("PEW PEW PEW", "EXPANDABLE LIST ADAPTER");
}
}
private static void populateTriggerVote(final ViewHolder holder, final Trigger trigger, final String imdbID){
DatabaseReference movieDB = FirebaseDatabase.getInstance().getReference("movies");
DatabaseReference triggerDB = movieDB.child(imdbID).child("Triggers").child(trigger.getId()).child("votes");
final DatabaseReference userDB = FirebaseDatabase.getInstance().getReference("users");
final ValueEventListener triggerListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("value").exists()) {
holder.voteTotal = dataSnapshot.child("value").getValue(int.class);
holder.total.setText(String.valueOf(holder.voteTotal));
}
else {
Log.d("Setting Value", "To Zero");
userDB.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("changes").child(imdbID).child("triggers").child(trigger.getId()).setValue(0);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
triggerDB.addValueEventListener(triggerListener);
}
}

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.

I want to display an image from drawable and combine it with data from json-api into recylerview

I have an application project for news media using java programming, I
want to display images for categories from drawable into recylerview
that are based on json-api, is there any one who can help me?
How I do for load image from drawable and combine it with data from json-api into RecylerView can anyone provide specific code here
this is my AdapterCategory.java
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Category> items = new ArrayList<>();
private Context ctx;
private OnItemClickListener mOnItemClickListener;
private int c;
public interface OnItemClickListener {
void onItemClick(View view, Category obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
// Provide a suitable constructor (depends on the kind of dataset)
public AdapterCategory(Context context, List<Category> items) {
this.items = items;
ctx = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name;
public TextView post_count;
public LinearLayout lyt_parent;
public ImageView imageView;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
post_count = (TextView) v.findViewById(R.id.post_count);
imageView = (ImageView)v.findViewById(R.id.image_category);
lyt_parent = (LinearLayout) v.findViewById(R.id.lyt_parent);
//imageView.setImageResource(image_array.length);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof ViewHolder) {
final Category c = items.get(position);
ViewHolder vItem = (ViewHolder) holder;
vItem.name.setText(Html.fromHtml(c.title));
vItem.post_count.setText(c.post_count + "");
Picasso.with(ctx).load(imageUri).into(vItem.imageView);
vItem.lyt_parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view, c, position);
}
}
});
}
}
public void setListData(List<Category> items){
this.items = items;
notifyDataSetChanged();
}
public void resetListData() {
this.items = new ArrayList<>();
notifyDataSetChanged();
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return items.size();
}
}
This is my FragmentCategory.java for display data
public class FragmentCategory extends Fragment {
private View root_view, parent_view;
private RecyclerView recyclerView;
private SwipeRefreshLayout swipe_refresh;
private AdapterCategory mAdapter;
private Call<CallbackCategories> callbackCall = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_category, null);
parent_view = getActivity().findViewById(R.id.main_content);
swipe_refresh = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_category);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewCategory);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setHasFixedSize(true);
//set data and list adapter
mAdapter = new AdapterCategory(getActivity(), new ArrayList<Category>());
recyclerView.setAdapter(mAdapter);
// on item list clicked
mAdapter.setOnItemClickListener(new AdapterCategory.OnItemClickListener() {
#Override
public void onItemClick(View v, Category obj, int position) {
ActivityCategoryDetails.navigate((ActivityMain) getActivity(), v.findViewById(R.id.lyt_parent), obj);
}
});
// on swipe list
swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mAdapter.resetListData();
requestAction();
}
});
requestAction();
return root_view;
}
private void displayApiResult(final List<Category> categories) {
mAdapter.setListData(categories);
swipeProgress(false);
if (categories.size() == 0) {
showNoItemView(true);
}
}
private void requestCategoriesApi() {
API api = RestAdapter.createAPI();
callbackCall = api.getAllCategories();
callbackCall.enqueue(new Callback<CallbackCategories>() {
#Override
public void onResponse(Call<CallbackCategories> call, Response<CallbackCategories> response) {
CallbackCategories resp = response.body();
if (resp != null && resp.status.equals("ok")) {
displayApiResult(resp.categories);
} else {
onFailRequest();
}
}
#Override
public void onFailure(Call<CallbackCategories> call, Throwable t) {
if (!call.isCanceled()) onFailRequest();
}
});
}
private void onFailRequest() {
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
showFailedView(true, getString(R.string.failed_text));
} else {
showFailedView(true, getString(R.string.no_internet_text));
}
}
private void requestAction() {
showFailedView(false, "");
swipeProgress(true);
showNoItemView(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestCategoriesApi();
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if(callbackCall != null && callbackCall.isExecuted()){
callbackCall.cancel();
}
}
private void showFailedView(boolean flag, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_category);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (flag) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction();
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_category);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_category);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipe_refresh.setRefreshing(show);
return;
}
swipe_refresh.post(new Runnable() {
#Override
public void run() {
swipe_refresh.setRefreshing(show);
}
});
}
And this is my ModeCategory.java
public class Category implements Serializable {
public int id = -1;
public String slug = "";
public String type = "";
public String url = "";
public String title = "";
public String title_plain = "";
public String content = "";
public String excerpt = "";
public String date = "";
public String modified = "";
public String description = "";
public int parent = -1;
public int post_count = -1;
public Author author;
public List<Category> categories = new ArrayList<>();
public List<Comment> comments = new ArrayList<>();
public List<Attachment> attachments = new ArrayList<>();
public CategoryRealm getObjectRealm(){
CategoryRealm c = new CategoryRealm();
c.id = id;
c.url = url;
c.slug = slug;
c.title = title;
c.description = description;
c.parent = parent;
c.post_count = post_count;
return c;
}
}

android expandable listview retrieve data from firebase

how can i use firebase to retrieve data for my Expandable listview. my firebase node is like this..
Adapter class:
public class CustomExpandableListViewAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> headerItem;
private HashMap<String, List<String>> childItem;
public CustomExpandableListViewAdapter(Context context, List<String> headerItem, HashMap<String, List<String>> childItem) {
this.context = context;
this.headerItem = headerItem;
this.childItem = childItem;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return childItem.get(headerItem.get(groupPosition)).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_items, null);
}
TextView tv = convertView.findViewById(R.id.tvChildItem);
tv.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return childItem.get(headerItem.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return headerItem.get(groupPosition);
}
#Override
public int getGroupCount() {
return headerItem.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_items, null);
}
TextView tv = convertView.findViewById(R.id.tvItemHeader);
tv.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
MainActivity :
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
CustomExpandableListViewAdapter customExpandableListViewAdapter;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Expandable ListView Data");
expandableListView = findViewById(R.id.expLv);
SetStandardGroups();
customExpandableListViewAdapter = new CustomExpandableListViewAdapter(this, listDataHeader, listDataChild);
expandableListView.setAdapter(customExpandableListViewAdapter);
}
public void SetStandardGroups() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
myRef.addChildEventListener(new ChildEventListener() {
int counter = 0;
List<String> childItem = new ArrayList<>();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
final String headerTitle = dataSnapshot.getKey();
listDataHeader.add(headerTitle);
Log.e("TAG", headerTitle);
for (DataSnapshot ds : dataSnapshot.getChildren()){
String child = (String) ds.getValue();
childItem.add(child);
}
listDataChild.put(listDataHeader.get(counter), childItem);
counter++;
Log.e("TAG", "counter :" + counter);
customExpandableListViewAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
The out put is this:
Out put
and i need Task1 the header tittle of first item and its contains 8 child's and like 2nd Task2 the header tittle of 2nd item and it will contains 5 child's
and 3rd Task3 the header tittle of 3rd item and will contain's 10 child how can i achieved please help me i new to firebase Thanks...
At last i found the problem. the problem is that i create a single Object of ArrayList for child which runs 3 times and save all data in one Object, so i found out that i need to create ArrayList Object Accordingly to loop Turn's which is 3.
this is the code which is working now.
myRef.addChildEventListener(new ChildEventListener() {
int counter = 0;
List<String> childItem;
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listDataHeader.add(dataSnapshot.getKey());
Log.e("TAG", listDataHeader.get(counter));
childItem = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String childNames = (String) ds.getValue();
Log.e("TAG", "childNames :" + childNames);
childItem.add(childNames);
}
listDataChild.put(listDataHeader.get(counter), childItem);
counter++;
Log.e("TAG", "counter :" + counter);
customExpandableListViewAdapter.notifyDataSetChanged();
}

Sort one of the array in multiple arrays inside list item

i have a custom listview that has 3 textview for Name, Unique id and Number of Absent and 1 image button for Delete in every list item. I tried to sort the number of absent, it sorts but the order breaks. I saw in internet the comparator and i think that's the solution to my problem but i don't know how to use it. Hoping that someone here can help me.
This is how i add values in my 3 ArrayList (mUid for unique id, MFullname for name, mStatus for Number of absent)
pagod = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents");
pagod.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String userid = child.child("userid").getValue().toString().trim();
String name = child.child("name").getValue().toString().trim();
mUid.add(userid);
mFullname.add(name);
//studentlist.invalidateViews();
//adapter.notifyDataSetChanged();
if (dataSnapshot.child(userid).child("attendance").exists()) {
pagodnapagod = FirebaseDatabase.getInstance().getReference();
Query query = pagodnapagod.child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(userid).child("attendance").child("finals").orderByChild("status").equalTo("absent");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String numberOfStudent ="Number of Absent: "+dataSnapshot.getChildrenCount();
//Toast.makeText(MyClassesActivity.this, numberOfStudent, Toast.LENGTH_SHORT).show();
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
String numberOfStudent = "Number of Absent: 0";
mStatus.add(numberOfStudent);
//Collections.sort(mStatus, Collections.reverseOrder());
adapters.notifyDataSetChanged();
progressDialog.dismiss();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is my custom adapter.
class Adapters extends BaseAdapter implements Filterable {
private Context context;
private int resource;
private int ids;
private ArrayList arrayList;
private List<String> originalData=null;
private List<String>filteredData=null;
private List<String> userId;
private List<String> status;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
private Adapters.ItemFilter mFilter = new Adapters.ItemFilter();
private LayoutInflater inflater;
public Adapters(Context context, int resource, int id, ArrayList arrayList, ArrayList userId, ArrayList status){
this.context = context;
this.resource = resource;
this.ids = id;
this.arrayList = arrayList;
this.filteredData = arrayList ;
this.originalData = arrayList ;
this.userId = userId;
this.status = status;
inflater = LayoutInflater.from(context);
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return position;
}
// Hold views of the ListView to improve its scrolling performance
private class ViewHolder {
public TextView type;
public TextView uid;
public TextView count;
public ImageButton removeButton;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
View rowView = convertView;
// Inflate the list_item.xml file if convertView is null
if(rowView==null){
rowView = inflater.inflate(R.layout.listitem6, null);
rowView= inflater.inflate(resource, parent, false);
Adapters.ViewHolder viewHolder = new Adapters.ViewHolder();
viewHolder.type= (TextView) rowView.findViewById(R.id.txt);
viewHolder.uid= (TextView) rowView.findViewById(R.id.id);
viewHolder.count= (TextView) rowView.findViewById(R.id.count);
viewHolder.removeButton= (ImageButton) rowView.findViewById(btn_del);
rowView.setTag(viewHolder);
}
final String x = (String) arrayList.get(position);
final String y = arrayList.get(position).toString().trim();
// Set text to each TextView of ListView item
Adapters.ViewHolder holder = (Adapters.ViewHolder) rowView.getTag();
holder.type.setText(x);
holder.uid.setText(x);
holder.count.setText(x);
holder.removeButton.setBackgroundResource(R.drawable.deletes);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
View parentRow = (View) view.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
TextView userId=(TextView) parentRow.findViewById(R.id.id);
TextView userName=(TextView) parentRow.findViewById(R.id.txt);
final String name = userName.getText().toString().trim();
final String uid = userId.getText().toString().trim();
//Toast.makeText(StudentListActivity.this, name +"\n" + uid, Toast.LENGTH_SHORT).show();
final AlertDialog.Builder builder2=new AlertDialog.Builder(context);
final View dialogView = inflater.inflate(R.layout.customdialog, null);
builder2.setView(dialogView);
final EditText input = (EditText) dialogView.findViewById(R.id.edit1);
final TextInputLayout inputs = (TextInputLayout) dialogView.findViewById(R.id.text_field);
TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
inputs.setErrorEnabled(false);
inputs.setError(null);
}
};
input.addTextChangedListener(watcher);
builder2.setTitle("Delete Class");
builder2.setMessage("Do you want to delete "+y+" from this class?");
builder2.setPositiveButton("ok", null);
builder2.setNegativeButton("cancel", null);
builder2.setIcon(R.drawable.deletes);
builder2.setCancelable(false);
final AlertDialog mAlertDialog = builder2.create();
mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button a = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
if (input.getText().toString().equalsIgnoreCase("delete")) {
arrayList.remove(position);
notifyDataSetChanged();
Toast.makeText(view.getContext(), y + " has been deleted in this class", Toast.LENGTH_SHORT).show();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("users").child("teacher").child(user.getUid().toString().trim()).child("class").child(aba).child(message).child("Listofstudents").child(uid);
mDatabase.setValue(null);
ref0 = FirebaseDatabase.getInstance().getReference();
ref0.child("usersclass").orderByChild("userid_classid").equalTo(uid+"-"+message).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String hello = child.getKey();
ref0.child("usersclass").child(hello).setValue(null);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialog.dismiss();
notifyDataSetChanged();
restartThis();
} else {
inputs.setError("Enter word DELETE");
}
}
});
Button b = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Do something
dialog.dismiss();
}
});
}
});
mAlertDialog.show();
}
});
holder.type.setText(filteredData.get(position));
holder.uid.setText(userId.get(position));
holder.count.setText(status.get(position));
return rowView;
}
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}

fill a TextView of activity from any class

I have a class called AdapterFilaProducto.java , class show certain information in the list.
This is my class
public class AdapterFilaProducto extends BaseAdapter {
protected Activity activity;
protected ArrayList<ItemFilaProducto> items;
protected ItemFilaProducto item;
protected String tipo;
protected Mascaras msk = new Mascaras();
public ImageButton btnImDerecha ;
public ImageButton btnImIzquierda;
public TextView producto;
private Venta contex;
TextView precio;
private BaseDataAdapter db;
private TextView precioCantidad;
public AdapterFilaProducto(Activity activity, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
}
public AdapterFilaProducto(Activity activity,Venta contex, ArrayList<ItemFilaProducto> items,String tipo) {
this.activity = activity;
this.items = items;
this.tipo = tipo;
this.contex=contex;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return items.get(position).getId();
}
public String getItemProducto(int position) {
return items.get(position).getProducto();
}
public String getItemCantidad(int position) {
return items.get(position).getCantidad();
}
public String getItemPercio(int position) {
return items.get(position).getPrecio();
}
public EditText getItemEdit(int position) {
return items.get(position).getEditTxt();
}
public View getView(int position, View convertView, ViewGroup parent)
{
db = new BaseDataAdapter(activity);
View vi=convertView;
final ItemFilaProducto item = items.get(position);
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.list_producto, null);
}
btnImDerecha = (ImageButton) vi.findViewById(R.id.BtnDerechaVenta);
btnImIzquierda = (ImageButton) vi.findViewById(R.id.BtnIzquierdaVenta);
TextView producto = (TextView) vi.findViewById(R.id.txtProductoVenta);
item.precio = (TextView) vi.findViewById(R.id.txtCantidadVenta);
item.edtxt = (EditText) vi.findViewById(R.id.editTxtListVenta);
producto.setText(item.getProducto());
Log.i("Precio",item.montoPrecio);
if(item.cantidad.equalsIgnoreCase("0")){
item.precio .setText(item.Precio);
}else
item.precio .setText(item.montoPrecio);
item.edtxt.setText(""+item.cantidad);
btnImDerecha.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
i=i+1;
item.edtxt.setText(""+i);
}
});
btnImIzquierda.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int i = Integer.parseInt(item.edtxt.getText().toString());
if(0<i){
i=i-1;
item.edtxt.setText(""+i);
}
}
});
item.edtxt.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
db.open();
Cursor cur = db.obtenerProductosTipo(tipo,item.getIdPro());
if(cur.moveToFirst()){
int precio = cur.getInt(3);
int cantidad = Integer.parseInt(item.edtxt.getText().toString());
int monto = precio*cantidad;
if(0 < monto){
item.setPrecio(msk.mascaraMontoTxt(String.valueOf(monto)));
item.precio .setText(item.getPrecio());
}
db.actualizarProductoMonto(item.getIdPro(),monto);
db.actualizarProductoCantidad(item.getIdPro(),cantidad);
}
cur.close();
int montoTotal = 0;
Cursor curAll = db.obtenerProductosTipo(tipo);
if(curAll.moveToFirst()){
do{
montoTotal = montoTotal + curAll.getInt(5);
Log.e("CANTIDAD", ""+curAll.getInt(5));
}while(curAll.moveToNext());
}
curAll.close();
try{
db.borrarTablaPar("MONTO");
}catch(Exception e){
}
Log.e("MONTO", ""+montoTotal);
DtoParametro dtoParametro = new DtoParametro();
dtoParametro.ID_PAR = "MONTO";
dtoParametro.VALOR = String.valueOf(montoTotal);
Log.i("MONTO",""+String.valueOf(montoTotal));
db.insertarParametro(dtoParametro);
db.close();
contex.mostrarMonto();
}
});
return vi;
}
}
And I need to do is to show in my main Activity is montoTotal. and display it in a total amount in the Textview for my Principal Activity .We tried several methods but none succeeded.
I would appreciate your help, thanks.
Its really hard to follow your code but you should either be able to make this an inner class of your PrincipalActivity and make montoTotal a member variable so that you can access it from where you need or create an instance of this class that retrieves the variable from a function

Categories

Resources