Recycler View items not changing. NotifyDataSetChanged is not working - android

I am developing an android application which shows list of items available for sale. I am using recycler view to display the list. I have a header for the recycler view and the header has 3 buttons for 3 categories (all, veg, non veg) and also meal type (breakfast/snacks).
And I have a bottom bar below the recycler view that has a button to show cart. Pressing that button opens another activity that list all the items in the cart.
User can increase or decrease the quantity of the item from the cart.
When user comes back from cart to menu page after modifying the contents of the cart(increasing/decreasing the quantities),sometimes the same quantity doesn't reflect on the menu page. I am notifying the adapter when user comes from cart to menu page. It gets changed after I scroll the list.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.CustomViewHolder> {
public RecyclerViewAdapter(Context context, List<MenuDescription> listOrder, DatabaseHandlerForCartAndMenu db,
List<MenuDescription> vegList, List<MenuDescription> nonVegList,
Tracker tracker, ArrayList<HashMap<String, String>> mealTypeList,
ArrayList<MenuDescription> firstMealTypeList, RecyclerView recyclerView) {
this.context = context;
this.db = db;
this.listOrder = firstMealTypeList;
this.vegList = vegList;
this.nonVegList = nonVegList;
this.completeList = firstMealTypeList;
this.tracker = tracker;
this.mealTypeList = mealTypeList;
this.globalList = listOrder;
mealTypeViewArray = new View[mealTypeList.size()];
previous_meal_type_id = mealTypeList.get(0).get(Constants.MEALTYPE_MENUID);
first_date = mealTypeList.get(0).get(Constants.DATE);
this.recyclerView = recyclerView;
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
}
#Override
public RecyclerViewAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view, parent, false);
menuList = view;
return new CustomViewHolder(view, viewType);
} else if (viewType == TYPE_HEADER) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);
return new CustomViewHolder(view, viewType);
}
return null;
}
#Override
public void onBindViewHolder(final RecyclerViewAdapter.CustomViewHolder holder, int position) {
try {
if (holder.HolderId == 1) {
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
final MenuDescription menu = listOrder.get(position - 1);
if (menu.getAvailable() >= 1) {
holder.addSubtractButtonsLayout.setVisibility(View.VISIBLE);
holder.overlayView.setVisibility(View.GONE);
holder.soldOutText.setVisibility(View.GONE);
} else {
holder.addSubtractButtonsLayout.setVisibility(View.INVISIBLE);
holder.overlayView.setVisibility(View.VISIBLE);
holder.soldOutText.setVisibility(View.VISIBLE);
}
if (menu.getDecr_button_visibility() == 1) {
holder.addSubtractLinearLayout.setVisibility(View.VISIBLE);
holder.addButton.setVisibility(View.GONE);
} else {
holder.addSubtractLinearLayout.setVisibility(View.GONE);
holder.addButton.setVisibility(View.VISIBLE);
}
holder.title.setText(menu.getName() + "");
holder.price.setText(menu.getPrice() + "");
holder.quant.setText(menu.getQuantity() + "");
holder.description.setText(menu.getDescription());
try {
Glide.with(context).load(menu.getImage_path()).placeholder(R.drawable.v3_placeholder_image).fitCenter().into(holder.image);
} catch (Exception e) {
e.printStackTrace();
}
holder.addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
menu.setDecr_button_visibility(1);
Constants.total_items_in_cart++;
Constants.total_price_of_cart += menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
tx.setText(Constants.total_items_in_cart + "");
try {
if (!db.CheckIsItemAlreadyInDBorNot(menu.getItem_id(), "cart", menu.getMenu_id())) {
menu.incrQuantity();
db.addDataToCartTable(menu);
// cart_items.add(menu);
holder.quant.setText(menu.getQuantity() + "");
} else {
menu.incrQuantity();
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
holder.quant.setText(menu.getQuantity() + "");
}
} catch (Exception e1) {
e1.printStackTrace();
}
holder.addSubtractLinearLayout.setVisibility(View.VISIBLE);
holder.addButton.setVisibility(View.GONE);
if (Constants.total_items_in_cart == 1) {
RecyclerViewMainActivity.bottomBarUp();
}
notifyDataSetChanged();
}
});
holder.incrementButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
menu.setDecr_button_visibility(1);
Constants.total_items_in_cart++;
Constants.total_price_of_cart += menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
tx.setText(Constants.total_items_in_cart + "");
try {
if (!db.CheckIsItemAlreadyInDBorNot(menu.getItem_id(), "cart", menu.getMenu_id())) {
menu.incrQuantity();
db.addDataToCartTable(menu);
holder.quant.setText(menu.getQuantity() + "");
} else {
menu.incrQuantity();
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
holder.quant.setText(menu.getQuantity() + "");
}
} catch (Exception e1) {
e1.printStackTrace();
}
notifyDataSetChanged();
}
});
holder.decrementButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tx = (TextView) ((Activity) context).findViewById(R.id.total);
totalPrice = (TextView) ((Activity) context).findViewById(R.id.totalPrice);
int qu = menu.getQuantity();
if (qu > 0) {
if (Constants.total_items_in_cart > 0) {
Constants.total_items_in_cart--;
tx.setText(Constants.total_items_in_cart + "");
Constants.total_price_of_cart -= menu.getPrice();
totalPrice.setText(Constants.total_price_of_cart + "");
}
if (Constants.total_items_in_cart == 0) {
RecyclerViewMainActivity.bottomBarDown();
}
menu.decrQuantity();
if (menu.getQuantity() == 0) {
holder.addSubtractLinearLayout.setVisibility(View.GONE);
holder.addButton.setVisibility(View.VISIBLE);
menu.setDecr_button_visibility(0);
try {
db.DeleteCartItem(menu.getItem_id(), menu.getMenu_id());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
try {
db.updateQuantityInCartTable(menu.getQuantity(), menu.getItem_id(), menu.getMenu_id());
} catch (Exception e1) {
e1.printStackTrace();
}
}
holder.quant.setText(menu.getQuantity() + "");
notifyDataSetChanged();
}
}
});
} else if (holder.HolderId == TYPE_HEADER) {
final LayoutInflater vi = (LayoutInflater) context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
for (int i = 0; i < mealTypeList.size(); i++) {
if (!mealTypeList.get(i).get(Constants.DATE).equals(first_date))
date_drop_down_clickable = true;
}
if (!date_drop_down_clickable)
holder.dateDropDown.setVisibility(View.GONE);
else holder.dateDropDown.setVisibility(View.VISIBLE);
} catch (Exception e) {
}
String frmDateStr;
try {
if (Constants.dateClickedFirstTimeByDefault) {
if (!Constants.dateSelected.equals("")) {
dateClicked(Constants.dateSelected);
previous_meal_type_id = "";
mealTypeClicked(mealTypeIdSelectedBeforeCartOpened, indexBeforeCartOpened);
} else {
String dateString = mealTypeList.get(0).get(Constants.DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
Date date = sdf.parse(dateString);
frmDateStr = getFormattedDate(date);
AttributedString as1 = new AttributedString(frmDateStr);
as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 2, 3);
holder.displaying_date.setText(frmDateStr);
dateClicked(dateString);
}
Constants.dateClickedFirstTimeByDefault = false;
}
if (Constants.keepAddingButtonOnCartPageClicked) {
Constants.keepAddingButtonOnCartPageClicked = false;
previous_meal_type_id = "";
mealTypeClicked(mealTypeIdSelectedBeforeCartOpened, indexBeforeCartOpened);
notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
holder.dateDropDownLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (date_drop_down_clickable) {
if (holder.horizontalScrollViewDateLayout.getVisibility() == View.GONE) {
holder.dateDropDown.setImageResource(R.drawable.pullup_red);
holder.horizontalScrollViewDateLayout.setVisibility(View.VISIBLE);
holder.dateLinearLayout.removeAllViews();
String previousDate = "";
int day = 0;
for (int i = 0; i < mealTypeList.size(); i++) {
if (!previousDate.equals(mealTypeList.get(i).get(Constants.DATE))) {
previousDate = mealTypeList.get(i).get(Constants.DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
try {
Date date = sdf.parse(previousDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
day = cal.get(Calendar.DATE);
} catch (ParseException e) {
e.printStackTrace();
}
View dateView = vi.inflate(R.layout.date_layout, null);
final TextView dateTextView = (TextView) dateView.findViewById(R.id.dateTextView);
if (day / 10 == 0)
dateTextView.setText("0" + Integer.toString(day));
else dateTextView.setText(Integer.toString(day));
dateTextView.setTag(previousDate);
if (i == previous_date_selected) {
dateTextView.setBackgroundResource(R.drawable.round_button_add);
dateTextView.setTextColor(context.getResources().getColor(R.color.white));
} else {
dateTextView.setBackgroundResource(0);
dateTextView.setTextColor(context.getResources().getColor(R.color.Description));
}
holder.dateLinearLayout.addView(dateView);
final String finalPreviousDate = previousDate;
final int finalI = i;
dateTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
holder.horizontalScrollViewDateLayout.setVisibility(View.GONE);
holder.dateDropDown.setImageResource(R.drawable.dropdown_red);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.US);
Date date = sdf.parse(dateTextView.getTag().toString());
String formattedDate = getFormattedDate(date);
AttributedString as1 = new AttributedString(formattedDate);
as1.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 2, 3);
holder.displaying_date.setText(formattedDate);
} catch (Exception e) {
}
previous_date_selected = finalI;
dateClicked(finalPreviousDate);
addingMealTypeLayoutToUI(holder, vi);
}
});
}
}
} else {
holder.horizontalScrollViewDateLayout.setVisibility(View.GONE);
holder.dateDropDown.setImageResource(R.drawable.dropdown_red);
}
}
}
});
addingMealTypeLayoutToUI(holder, vi);
holder.all.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = completeList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 0;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.veg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = vegList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 1;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.nonVeg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listOrder = nonVegList;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
previous_filter_selected = 2;
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
notifyDataSetChanged();
}
});
holder.filterLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.buttonLayout.getVisibility() == View.VISIBLE)
holder.buttonLayout.setVisibility(View.GONE);
else if (holder.buttonLayout.getVisibility() == View.GONE)
holder.buttonLayout.setVisibility(View.VISIBLE);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void dateClicked(String dateValueSelected) {
mealTypeListForSelectDate = new ArrayList<>();
for (int i = 0; i < mealTypeList.size(); i++) {
if (dateValueSelected.equals(mealTypeList.get(i).get(Constants.DATE))) {
mealTypeListForSelectDate.add(mealTypeList.get(i));
previous_view_selected = 0;
Constants.dateSelected = dateValueSelected;
}
}
}
private void addingMealTypeLayoutToUI(RecyclerViewAdapter.CustomViewHolder holder, LayoutInflater vi) {
try {
holder.mealtype_layout.removeAllViews();
for (int i = 0; i < mealTypeListForSelectDate.size(); i++) {
HashMap<String, String> mealtype_hashmap = mealTypeListForSelectDate.get(i);
mealTypeViewArray[i] = vi.inflate(R.layout.meal_type_name_layout, null);
final TextView myButton = (TextView) mealTypeViewArray[i].findViewById(R.id.mealTypeTextView);
String mealType = mealtype_hashmap.get(Constants.MEAL_TYPE);
myButton.setText(mealType);
myButton.setTag(mealtype_hashmap.get(Constants.MEALTYPE_MENUID));
if (i == previous_view_selected) {
myButton.setBackgroundResource(R.drawable.header_meal_type_selected);
myButton.setTextColor(context.getResources().getColor(R.color.ColorPrimaryDark));
mealTypeClicked(myButton.getTag().toString(), i);
} else {
myButton.setBackgroundResource(R.drawable.header_meal_type_not_selected);
myButton.setTextColor(context.getResources().getColor(R.color.Description));
}
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
lp.topMargin = 10;
lp.weight = 1;
holder.mealtype_layout.addView(mealTypeViewArray[i], lp);
final int finalI = i;
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mealTypeClicked(myButton.getTag().toString(), finalI);
}
});
}
} catch (Exception e) {
}
}
private void mealTypeClicked(String mealTypeMenuId, int index) {
try {
if (!previous_meal_type_id.equals(mealTypeMenuId)) {
Constants.mealTypeMenuIdSelected = mealTypeMenuId;
List<MenuDescription> MealType_list = new ArrayList<>();
vegList.clear();
nonVegList.clear();
previous_view_selected = index;
for (int i = 0; i < globalList.size(); i++) {
if (mealTypeMenuId.equals(globalList.get(i).getMenu_id())) {
MealType_list.add(globalList.get(i));
}
}
for (int i = 0; i < MealType_list.size(); i++) {
if (MealType_list.get(i).getCatId().equals("true")) {
vegList.add(MealType_list.get(i));
} else if (MealType_list.get(i).getCatId().equals("false")) {
nonVegList.add(MealType_list.get(i));
}
}
try {
completeList = MealType_list;
if (previous_filter_selected == 0)
listOrder = completeList;
else if (previous_filter_selected == 1)
listOrder = vegList;
else if (previous_filter_selected == 2)
listOrder = nonVegList;
previous_meal_type_id = mealTypeMenuId;
mealTypeIdSelectedBeforeCartOpened = previous_meal_type_id;
indexBeforeCartOpened = index;
if (nothingForThisCategory.isShown())
nothingForThisCategory.dismiss();
if (listOrder.size() == 0) {
nothingForThisCategory = Snackbar.make(recyclerView, "Nothing is present for this category", Snackbar.LENGTH_INDEFINITE);
nothingForThisCategory.show();
}
notifyDataSetChanged();
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
#Override
public int getItemCount() {
return (null != listOrder ? listOrder.size() + 1 : 0);
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}

Related

How to fix memory leaks for view created and added dynamically by removing all views?

I have a custom class to generate dynamically view by my generate() method but when i call finish() method in my activity gc doesn't work and memory up to 10 MB for every activity call (using checking on Profiler), I need to fix it with manual delete view from memory with gc, I know gc do it when i have no strong reference to my views and i followed this rules and save all my views to collection as WeakHashMap but gc doesn't deallocation for my views:
public class CustomQuestionAdapter {
public ArrayList<Question> items;
private Context mActivity;
private boolean isDisabled = false;
private String TAG = "CUSTOM_QUESTION_ADAPTER";
private OnProgressViewChanged onProgressViewChanged;
private WeakHashMap<String, View> boxReferences = new WeakHashMap<>();
private SparseArray<EditTextPlus> textViewsReferences = new SparseArray<>();
public CustomQuestionAdapter(Context context) {
this.mActivity = context;
}
public void setItems(ArrayList<Question> items) {
this.items = items;
}
public void generate(int index) {
int total = items.size();
generateBoxes(index);
this.onProgressViewChanged.onChanged((int) ((index * 1.0 / total) * 100));
if ( index < total - 1){
this.onProgressViewChanged.onFinish(boxReferences.get(items.get(index).getQId().toString()), false);
}else{
this.onProgressViewChanged.onChanged(100);
this.onProgressViewChanged.onFinish(boxReferences.get(items.get(index).getQId().toString()), true);
}
}
public void removeAllView(ViewGroup v){
for (View view: boxReferences.values()){
try{
view.setVisibility(View.VISIBLE);
((ViewGroup) view).removeAllViews();
Log.d(TAG, "removeAllView: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ removed ");
}catch (Exception e){
Log.d(TAG, "removeAllView: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ occured error" );
}
}
if (v != null){
v.removeAllViews();
}
boxReferences = null;
textViewsReferences = null;
items.clear();
}
public void setDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}
#Nullable
private View generateBoxes(final int position) {
final Question item = items.get(position);
final HashMap<String, String> options = item.getOptionsHashMap();
item.setQText(String.format("(%d) %s", position + 1, item.getQText()));
if (item.getQType().equals("Text")) {
// final View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_text, null, false);
View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_text, null, false);
try {
((TextViewPlus) layoutView.findViewById(R.id.question)).setText(String.format("%s%s", item.getQText(), Boolean.valueOf(options.get("required")) ? " (الزامی)" : ""));
} catch (Exception e) {
e.printStackTrace();
}
EditTextPlus answerText = layoutView.findViewById(R.id.answer);
textViewsReferences.put(position, answerText);
answerText.setText(item.getAnswer());
if (isDisabled)
answerText.setEnabled(false);
layoutView.setVisibility(item.getShouldHide() ? View.GONE : View.VISIBLE);
boxReferences.put(item.getQId().toString(), layoutView);
return layoutView;
} else if (item.getQType().equals("Checkbox")) {
View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_radio, null, false);
LinearLayout optionsLayout = layoutView.findViewById(R.id.options);
try {
((TextViewPlus) layoutView.findViewById(R.id.question)).setText(String.format("%s%s", item.getQText(), Boolean.valueOf(options.get("required")) ? " (الزامی)" : ""));
} catch (Exception e) {
e.printStackTrace();
}
// new Thread(new Runnable() {
// #Override
// public void run() {
optionsLayout.removeAllViews();
final List<CheckBox> checkBoxes = new ArrayList<>();
for (int i = 0; i < item.getFields().size(); i++) {
Field field = item.getFields().get(i);
View view = LayoutInflater.from(mActivity).inflate(R.layout.template_checkbox, null);
CheckBox checkBox = view.findViewById(R.id.radio);
TextViewPlus titleText = view.findViewById(R.id.title);
if (isDisabled)
checkBox.setEnabled(false);
checkBox.setChecked(item.getAnswer().contains(field.getName() + "|"));
checkBox.setTag(field.getName());
titleText.setText(field.getTitle());
optionsLayout.addView(view);
checkBoxes.add(checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
StringBuilder answer = new StringBuilder();
for (CheckBox checkBox1 : checkBoxes) {
if (checkBox1.isChecked()) {
answer.append(checkBox1.getTag()).append("|");
}
}
// answers.set(position, answer);
item.setAnswer(answer.toString());
}
});
}
// }
// }).start();
boxReferences.put(item.getQId().toString(), layoutView);
layoutView.setVisibility(item.getShouldHide() ? View.GONE : View.VISIBLE);
return layoutView;
} else if (item.getQType().equals("Input")) {
View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_input, null, false);
try {
((TextViewPlus) layoutView.findViewById(R.id.question)).setText(String.format("%s%s", item.getQText(), Boolean.valueOf(options.get("required")) ? " (الزامی)" : ""));
EditTextPlus answerText = layoutView.findViewById(R.id.answer);
switch (options.get("type")) {
case "text": {
answerText.setInputType(InputType.TYPE_CLASS_TEXT);
break;
}
case "number": {
answerText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
break;
}
case "date": {
answerText.setInputType(InputType.TYPE_CLASS_DATETIME);
break;
}
}
textViewsReferences.put(position, answerText);
answerText.setText(item.getAnswer());
if (isDisabled)
answerText.setEnabled(false);
} catch (Exception e) {
e.printStackTrace();
}
boxReferences.put(item.getQId().toString(), layoutView);
layoutView.setVisibility(item.getShouldHide() ? View.GONE : View.VISIBLE);
return layoutView;
} else if (item.getQType().equals("Radio Button")) {
View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_radio_with_group, null, false);
LinearLayout textGroup = layoutView.findViewById(R.id.textGroup);
RadioGroup radioGroup = layoutView.findViewById(R.id.radioGroup);
try {
((TextViewPlus) layoutView.findViewById(R.id.question)).setText(String.format("%s%s", item.getQText(), Boolean.valueOf(options.get("required")) ? " (الزامی)" : ""));
} catch (Exception e) {
e.printStackTrace();
}
textGroup.removeAllViews();
radioGroup.removeAllViews();
for (int i = 0; i < item.getFields().size(); i++) {
final Field field = item.getFields().get(i);
final RadioButton radioButton = new RadioButton(mActivity);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 70));
radioButton.setGravity(Gravity.CENTER);
radioButton.setChecked(false);
radioButton.setId(View.generateViewId());
TextViewPlus titleText = new TextViewPlus(mActivity) {{
setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 70) {{
rightMargin = 10;
}});
setEllipsize(TextUtils.TruncateAt.MARQUEE);
setFont(mActivity, "fonts/IRANYekanWebLight.ttf");
setTextSize(Dimension.SP, 14f);
setGravity(Gravity.CENTER | Gravity.RIGHT);
setTextColor(mActivity.getResources().getColor(R.color.gray));
}};
radioButton.setChecked(item.getAnswer().equals(field.getName()));
radioButton.setTag(field.getName());
if (isDisabled) {
radioButton.setEnabled(false);
}
titleText.setText(field.getTitle());
textGroup.addView(titleText);
radioGroup.addView(radioButton);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
item.setAnswer(field.getName());
// items.set(position, item);
}
//
}
});
}
if (isDisabled) {
radioGroup.setEnabled(false);
}
// }
// }).start();
boxReferences.put(item.getQId().toString(), layoutView);
layoutView.setVisibility(item.getShouldHide() ? View.GONE : View.VISIBLE);
return layoutView;
} else if (item.getQType().equals("OPTCheckbox")) {
View layoutView = LayoutInflater.from(mActivity).inflate(R.layout.adapter_question_radio, null, false);
LinearLayout optionsLayout = layoutView.findViewById(R.id.options);
// new Thread(new Runnable() {
// #Override
// public void run() {
try {
((TextViewPlus) layoutView.findViewById(R.id.question)).setText(String.format("%s%s", item.getQText(), Boolean.valueOf(options.get("required")) ? " (الزامی)" : ""));
} catch (Exception e) {
e.printStackTrace();
}
optionsLayout.removeAllViews();
Field field = item.getFields().get(0);
View view = LayoutInflater.from(mActivity).inflate(R.layout.template_checkbox, null);
final CheckBox checkBox = view.findViewById(R.id.radio);
TextViewPlus titleText = view.findViewById(R.id.title);
if (isDisabled)
checkBox.setEnabled(false);
Log.e("~~~~~~~", item.getAnswer());
if (item.getAnswer().contains(field.getName() + "|")) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
checkBox.setTag(field.getName());
checkBox.setId((int) 123);
titleText.setText(field.getTitle());
optionsLayout.addView(view);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
item.setAnswer(b ? checkBox.getTag() + "|" : "");
// items.set(position, item);
try {
JSONArray toToggleItems = new JSONArray(item.getOptionsHashMap().get("hidden_ls"));
for (int i = 0; i < toToggleItems.length(); i++) {
for (int j = 0; j < items.size(); j++) {
if (items.get(j).getQId().toString().equals(toToggleItems.getString(i))) {
items.get(j).setShouldHide(!b);
try {
boxReferences.get(items.get(j).getQId().toString()).setVisibility(!b ? View.GONE : View.VISIBLE);
} catch (Exception ignored) {
}
if (!b && items.get(j).getOptionsHashMap().containsKey("hidden_ls")) {
try {
((CheckBox) boxReferences.get(items.get(j).getQId().toString()).findViewById((int) 123)).setChecked(false);
} catch (Exception ignored) {
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
// }
// }).start();
boxReferences.put(item.getQId().toString(), layoutView);
layoutView.setVisibility(item.getShouldHide() ? View.GONE : View.VISIBLE);
return layoutView;
}
return null;
}
public void prepareItemsForValidation(int position) {
try {
items.get(position).setAnswer(textViewsReferences.get(position).getText().toString());
} catch (Exception ignored) {
}
}
public int getItemViewType(int position) {
final Question item = items.get(position);
// Log.e(TAG, "type:"+item.type);
switch (item.getQType()) {
case "Text":
return VIEW_TYPE_TEXT;
case "Checkbox":
return VIEW_TYPE_CHECKBOX;
case "Input":
return VIEW_TYPE_INPUT;
case "Radio Button":
return VIEW_TYPE_RADIO;
case "OPTCheckbox":
return VIEW_TYPE_OPTCHECKBOX;
}
return VIEW_TYPE_TEXT;
// return super.getItemViewType(position);
}
public void setOnProgressViewChanged(OnProgressViewChanged onProgressViewChanged) {
this.onProgressViewChanged = onProgressViewChanged;
}
public interface OnProgressViewChanged {
void onChanged(int progress);
void onFinish(View view, Boolean lastIndex);
}
}
Even in activity i called removeAll() method in destroy() method :
#Override
protected void onDestroy() {
adapter.removeAllView(insideContainer);
System.gc();
super.onDestroy();
}
I found that every time we call the gc, the gc doesn't do its job. In fact, by following a number of things, such as not keeping a strong reference from the View in memory, the gc will be able to remove the heap while the heap is full. So because WeakHashMap has been used, gc will delete it on time. Otherwise, it wouldn't have happened if I had used HashMap.

Recycler view swaps items when i scroll them

I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back

Why my json data not following an order in API 16 and lower API?

Explanation:I have json.In which, i have object namely matches.Inside the matches object i have lot of objects.I mean data->season->matches->object1,2,3 so on.
This objects are dynamic it's not fixed at the run-time.I tried to parse the matches object.
Here is my json data
Now i tried to parse this file using my url.I was used a volley network library to parse the json file from server.
Here is my code to parse the json and get the response
public class SeriesActivity extends AppCompatActivity {
Toolbar toolbar;
String series_key = "";
String url = "";
String access_token = "";
FrameLayout frameLayout;
List<SeriesMatches> series_header;
HashMap<SeriesMatches, List<SeriesMatches>> series_child;
String winner_team = "";
String overs = "";
String wickets_now = "";
String now_runs = "";
String now_bat_team = "";
String fullScore = "";
String team_name = "";
String[] over_parts;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
frameLayout = (FrameLayout) findViewById(R.id.adbar);
new AddLoader(getApplicationContext()).LoadAds(frameLayout);
SharedPreferences sharedPreferences = this.getSharedPreferences("SaveTime", MODE_PRIVATE);
access_token = sharedPreferences.getString("accessToken", null);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
Intent intent = getIntent();
series_key = intent.getStringExtra("series_key");
url = "https://api.litzscore.com/rest/v2/season/" + series_key + "/?access_token=" + access_token + "&card_type=summary_card";
if (!Utils.isNetworkConnected(this)) {
dialog_popup();
} else {
getSeriesMatches();
}
}
public void getSeriesMatches() {
String str_req = "getSeries";
StringRequest matches_req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject object = new JSONObject(response);
if (!object.getBoolean("status") || object.getString("status_code").equals("403")) {
// DialogAbandoned abandoned=new DialogAbandoned(getApplicationContext());
// abandoned.setDialog("Series","Data Coming soon...");
} else {
series_header = new ArrayList<>();
series_child = new HashMap<>();
if (object.has("data") && !object.isNull("data")) {
JSONObject data = object.getJSONObject("data");
JSONObject season;
JSONObject matches;
if (data.has("season") && !data.isNull("season")) {
season = data.getJSONObject("season");
if (season.has("matches") && !season.isNull("matches")) {
matches = season.getJSONObject("matches");
JSONArray matches_arr = matches.names();
JSONObject matches_obj;
for (int i = 0; i < matches_arr.length(); i++) {
SeriesMatches s_matches = new SeriesMatches();
matches_obj = matches.getJSONObject(matches_arr.getString(i));
JSONObject teams = matches_obj.getJSONObject("teams");
JSONObject team_a = teams.getJSONObject("a");
JSONObject team_b = teams.getJSONObject("b");
JSONObject start_date = matches_obj.getJSONObject("start_date");
s_matches.setRealted_name(matches_obj.getString("related_name"));
series_header.add(s_matches);
if (!matches_obj.isNull("msgs") && matches_obj.has("msgs")) {
JSONObject msgs = matches_obj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
}
}
JSONObject now;
now_bat_team = "";
now_runs = "";
wickets_now = "";
overs = "";
if (matches_obj.has("now") && !matches_obj.isNull("now")) {
now = matches_obj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if (now.getString("runs_str").equals("null")) {
overs = "0";
} else {
over_parts = now.getString("runs_str").split(" ");
overs = over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
team_name = "";
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
if (matches_obj.has("status_overview") && !matches_obj.isNull("status_overview")) {
if (matches_obj.getString("status_overview").equals("abandoned") || matches_obj.getString("status_overview").equals("canceled")) {
fullScore = "";
} else {
fullScore = team_name + " - " + now_runs + "/" + wickets_now + " (" + overs + " ovr)";
}
}
SeriesMatches s2 = new SeriesMatches();
s2.setTeam_Aname(team_a.getString("short_name"));
s2.setTemm_Akey(team_a.getString("key"));
s2.setTeam_Bname(team_b.getString("short_name"));
s2.setTeam_Bkey(team_b.getString("key"));
s2.setStatus(matches_obj.getString("status"));
s2.setDate(start_date.getString("iso"));
s2.setVenue(matches_obj.getString("venue"));
s2.setMsgs(winner_team);
s2.setScore(fullScore);
s2.setMom(matches_obj.getString("man_of_match"));
List<SeriesMatches> matches_info = new ArrayList<>();
matches_info.add(s2);
series_child.put(series_header.get(i), matches_info);
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ExpandedListAdapter adapter = new ExpandedListAdapter(getApplicationContext(), series_header, series_child);
expListView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog_popup();
} else if (error instanceof AuthFailureError) {
dialog_popup();
} else if (error instanceof ServerError) {
dialog_popup();
} else if (error instanceof NetworkError) {
dialog_popup();
} else if (error instanceof ParseError) {
dialog_popup();
}
}
});
AppController.getInstance().addToRequestQueue(matches_req, str_req);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is my Expnadedlistview
public class ExpandedListAdapter extends BaseExpandableListAdapter{
private Context context;
private List<SeriesMatches> series_header;
private HashMap<SeriesMatches,List<SeriesMatches>> series_child;
private Typeface tf;
public ExpandedListAdapter(Context context,List<SeriesMatches> series_header,HashMap<SeriesMatches,List<SeriesMatches>> series_child){
this.context=context;
this.series_header=series_header;
this.series_child=series_child;
}
#Override
public int getGroupCount() {
return this.series_header.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.series_header.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_group,null);
}
TextView text_group=(TextView)convertView.findViewById(R.id.lblListHeader);
SeriesMatches s=series_header.get(groupPosition);
text_group.setText(s.getRealted_name());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_child,null);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
}
TextView teamA=(TextView)convertView.findViewById(R.id.txt_one_country_name);
TextView teamB=(TextView)convertView.findViewById(R.id.txt_two_country_name);
TextView txt_venue=(TextView)convertView.findViewById(R.id.venue);
TextView txtTimeIST=(TextView)convertView.findViewById(R.id.txt_timeist);
TextView txtTimeGMT=(TextView)convertView.findViewById(R.id.txt_timegmt);
TextView txtDate=(TextView)convertView.findViewById(R.id.txt_date);
ImageView team_one_flag_icon=(ImageView)convertView.findViewById(R.id.team_one_flag_icon);
ImageView team_two_flag_icon=(ImageView)convertView.findViewById(R.id.team_two_flag_icon);
SeriesMatches s1=series_child.get(series_header.get(groupPosition)).get(childPosition);
String team_a_key=s1.getTemm_Akey();
String team_b_key=s1.getTeam_Bkey();
teamA.setText(s1.getTeam_Aname());
teamB.setText(s1.getTeam_Bname());
if(team_a_key.equals("ind")) {
team_one_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_a_key.equals("omn")){
team_one_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_a_key.equals("afg")) {
team_one_flag_icon.setImageResource(R.drawable.afg);
} else if(team_a_key.equals("aus")) {
team_one_flag_icon.setImageResource(R.drawable.aus);
} else if(team_a_key.equals("ban")) {
team_one_flag_icon.setImageResource(R.drawable.ban);
} else if(team_a_key.equals("eng")) {
team_one_flag_icon.setImageResource(R.drawable.eng);
} else if(team_a_key.equals("hkg")) {
team_one_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_a_key.equals("ire")) {
team_one_flag_icon.setImageResource(R.drawable.ire);
} else if(team_a_key.equals("nl")) {
team_one_flag_icon.setImageResource(R.drawable.nl);
} else if(team_a_key.equals("nz")) {
team_one_flag_icon.setImageResource(R.drawable.nz);
} else if(team_a_key.equals("pak")) {
team_one_flag_icon.setImageResource(R.drawable.pak);
} else if(team_a_key.equals("rsa")) {
team_one_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_a_key.equalsIgnoreCase("sl")) {
team_one_flag_icon.setImageResource(R.drawable.sl);
} else if (team_a_key.equals("uae")) {
team_one_flag_icon.setImageResource(R.drawable.uae);
} else if (team_a_key.equals("wi")) {
team_one_flag_icon.setImageResource(R.drawable.wi);
} else if (team_a_key.equals("zim")) {
team_one_flag_icon.setImageResource(R.drawable.zim);
} else if(team_a_key.equals("sct")) {
team_one_flag_icon.setImageResource(R.drawable.sct);
////////// IPL Team ///////////
} else if(team_a_key.equals("dd")) {
team_one_flag_icon.setImageResource(R.drawable.dd);
} else if(team_a_key.equals("kkr")) {
team_one_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_a_key.equals("mi")) {
team_one_flag_icon.setImageResource(R.drawable.mi);
} else if(team_a_key.equals("srh")) {
team_one_flag_icon.setImageResource(R.drawable.sh);
} else if(team_a_key.equals("kxip")) {
team_one_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_a_key.equals("rcb")) {
team_one_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_a_key.equals("rps")) {
team_one_flag_icon.setImageResource(R.drawable.rps);
} else if(team_a_key.equals("gl")) {
team_one_flag_icon.setImageResource(R.drawable.gl);
} else {
team_one_flag_icon.setImageResource(R.drawable.dft);
}
//for B TEAM
if(team_b_key.equals("ind")) {
team_two_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_b_key.equals("omn")){
team_two_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_b_key.equals("afg")) {
team_two_flag_icon.setImageResource(R.drawable.afg);
} else if(team_b_key.equals("aus")) {
team_two_flag_icon.setImageResource(R.drawable.aus);
} else if(team_b_key.equals("ban")) {
team_two_flag_icon.setImageResource(R.drawable.ban);
} else if(team_b_key.equals("eng")) {
team_two_flag_icon.setImageResource(R.drawable.eng);
} else if(team_b_key.equals("hkg")) {
team_two_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_b_key.equals("ire")) {
team_two_flag_icon.setImageResource(R.drawable.ire);
} else if(team_b_key.equals("nl")) {
team_two_flag_icon.setImageResource(R.drawable.nl);
} else if(team_b_key.equals("nz")) {
team_two_flag_icon.setImageResource(R.drawable.nz);
} else if(team_b_key.equals("pak")) {
team_two_flag_icon.setImageResource(R.drawable.pak);
} else if(team_b_key.equals("rsa")) {
team_two_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_b_key.equalsIgnoreCase("sl")) {
team_two_flag_icon.setImageResource(R.drawable.sl);
} else if (team_b_key.equals("uae")) {
team_two_flag_icon.setImageResource(R.drawable.uae);
} else if (team_b_key.equals("wi")) {
team_two_flag_icon.setImageResource(R.drawable.wi);
} else if (team_b_key.equals("zim")) {
team_two_flag_icon.setImageResource(R.drawable.zim);
} else if(team_b_key.equals("sct")) {
team_two_flag_icon.setImageResource(R.drawable.sct);
////////// IPL ///////////
} else if(team_b_key.equals("dd")) {
team_two_flag_icon.setImageResource(R.drawable.dd);
} else if(team_b_key.equals("kkr")) {
team_two_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_b_key.equals("mi")) {
team_two_flag_icon.setImageResource(R.drawable.mi);
} else if(team_b_key.equals("srh")) {
team_two_flag_icon.setImageResource(R.drawable.sh);
} else if(team_b_key.equals("kxip")) {
team_two_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_b_key.equals("rcb")) {
team_two_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_b_key.equals("rps")) {
team_two_flag_icon.setImageResource(R.drawable.rps);
} else if(team_b_key.equals("gl")) {
team_two_flag_icon.setImageResource(R.drawable.gl);
} else {
team_two_flag_icon.setImageResource(R.drawable.dft);
}
try {
String[] fullDate;
String fullTime = "";
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'+00':ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
String ist=outputFormat.format(utcFormat.parse(s1.getDate()));
Date timestamp;
timestamp = utcFormat.parse(s1.getDate());
fullDate = timestamp.toString().split(" ");
String monthName = fullDate[1];
String Dayname = fullDate[2];
fullTime = fullDate[3];
String[] gmt_fulldate = s1.getDate().split("T");
String gmt_time = gmt_fulldate[1];
String[] gmt_hour_parts = gmt_time.split("\\+");
String finalDate = Dayname + " " + monthName;
String finalTimeIST = ist + " IST | " + gmt_hour_parts[0] + " GMT";
String[] venue_parts=s1.getVenue().split(",");
int length=venue_parts.length;
if(length==1){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
txtTimeGMT.setText(venue_parts[0]);
}
if(length==2){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
txtTimeGMT.setText(venue_parts[0] + "," + venue_parts[1]);
}
if(length==3){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[1] + "," + venue_parts[2]);
}
if(length==4){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[2] + "," + venue_parts[3]);
}
if(s1.getStatus().equals("notstarted")){
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
txtDate.setTypeface(tf);
txtDate.setText("Started on " + finalDate);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(finalTimeIST);
}
if(s1.getStatus().equals("completed")){
txtDate.setTypeface(tf);
txtDate.setText(s1.getScore());
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(s1.getMsgs());
Log.e("NOTSTARTED","DONE");
txt_venue.setText("MOM : "+s1.getMom().substring(0, 1).toUpperCase() + s1.getMom().substring(1).replace("_", " "));
}
}
catch (ParseException e){
e.printStackTrace();
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Problem is i have mobile in which jellybean is installed.In the jellybean or lower of jellybean it's not comes in the order.If same code i ran into lollipop or marshmallow it's comes into the order.Order like
trieseries_2016_g1
trieseries_2016_g2
until trieseries_2016_final
Here is a screenshort of marshmallow
please, help me to solve out this problem.
Here is a sceenshort of jellybean

Adding dynamic items to linearlayout displays reverse order android

I'm inflating dynamic view to linear layout but it displays reversely.
try {
JSONArray jsonArray = new JSONArray(tooteet.getMeasureJson());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Measure measureData = new Measure();
measureData.id = jsonObject.optString("id");;
measureData.tooteetId = jsonObject.optString("tooteetId");
measureData.laneId = jsonObject.optString("laneId");
measureData.startDate = jsonObject.optString("startDate");
measureData.endDate = jsonObject.optString("endDate");
measureData.description = jsonObject.optString("text");
measureData.value = jsonObject.optDouble("value");
measureData.measureTypeId = jsonObject.optInt("measureTypeId");
measureData.description = jsonObject.optString("text");
measureData.isTimeSet =jsonObject.optBoolean("isTimeSet");
mMeasureList.add(measureData);
addMeasureView(measureData, i);
}
} catch (Exception e) {
Log.d("FeedMeasure", "Exception: "+e.toString());
}
where i'm getting log value for tooteet.getMeasureJson() is
onCreate -- tooteet.getMeasureJson(): [{"id":"3fb2af41-201d-4aca-9479-42af6cca5947","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":11111,"text":"","measureTypeId":1,"isTimeSet":false},{"id":"ecab9659-7eb5-417a-8f5e-f769629957ae","tooteetId":"3d923a95-d8d8-4478-b336-c995cc77407d","laneId":"00000000-0000-0000-0000-000000000000","value":22222,"text":"","measureTypeId":1,"isTimeSet":false}]
Here I'm adding measure view using below method
private void addMeasureView(final Measure measure, int position) {
Log.d("ss","adding measure data value ________________"+measure.value+" position __________"+position);
final View parent = getLayoutInflater().inflate(R.layout.view_measure_tooteet_item, mDisplayContainer, false);
final TextView txtDescription, txtValues, txtStartDateTime, txtEndDateTime, labelTaxIncluded, labelTaxColon;
final ImageView imgEdit, imgDelete;
final LinearLayout lnrDescription, lnrStartLayout, lnrEndLayout;
final View mViewDivider;
txtDescription = (TextView) parent.findViewById(R.id.txt_description);
txtValues = (TextView) parent.findViewById(R.id.values);
txtStartDateTime = (TextView) parent.findViewById(R.id.start_date_and_time);
txtEndDateTime = (TextView) parent.findViewById(R.id.end_date_and_time);
mViewDivider = (View) parent.findViewById(R.id.view_divider);
imgEdit = (ImageView) parent.findViewById(R.id.edit);
imgDelete = (ImageView) parent.findViewById(R.id.delete);
lnrDescription = (LinearLayout) parent.findViewById(R.id.lnr_description);
lnrStartLayout = (LinearLayout) parent.findViewById(R.id.lnr_start_layout);
lnrEndLayout = (LinearLayout) parent.findViewById(R.id.lnr_end_layout);
if(tooteet.isOwner(getUserPreference())){
imgDelete.setVisibility(View.VISIBLE);
imgEdit.setVisibility(View.VISIBLE);
}else{
imgDelete.setVisibility(View.GONE);
imgEdit.setVisibility(View.GONE);
}
if(measure.getValue() > 0) {
txtValues.setVisibility(View.VISIBLE);
if (measure.getValue() % 1 == 0) {
txtValues.setText("" + (int) measure.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
} else {
txtValues.setText("" + measure.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measure.getMeasureTypeId()));
}
}else{
txtValues.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measure.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getStartDate())) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTime(measure.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measure.getEndDate())) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTime(measure.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
//
// if(position < mMeasureList.size()){
// mViewDivider.setVisibility(View.VISIBLE);
// }else{
// mViewDivider.setVisibility(View.GONE);
// }
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setTitle(R.string.delete);
builder.setMessage(R.string.delete_tooteet_measure_tuple);
builder.setPositiveButton(R.string.yes_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
getDairyLineApi().deleteMeasureTooteet(mMeasureList.get(pos).getId(), tooteet.getLaneId(), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.deleted_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDisplayContainer.removeView(parent);
mMeasureList.remove(pos);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
});
builder.setNegativeButton(R.string.no_caps, null);
builder.create().show();
}
});
imgEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int pos = (Integer) v.getTag();
MeasureTooteetSelector measureTooteetSelector = new MeasureTooteetSelector();
measureTooteetSelector.openMeasureDetailSelector(FeedMeasureDetailsActivity.this, mMeasureList.get(pos),
new MeasureTooteetSelector.OnMeasureDetailSelectListener() {
#Override
public void onMeasureSelect(final Measure measureData) {
if (!BDevice.isInternetConnected(FeedMeasureDetailsActivity.this)) {
AlertUtils.showNetworkAlert(FeedMeasureDetailsActivity.this);
return;
}
final Dialog pd = UiUtils.getSpinnerDialog(FeedMeasureDetailsActivity.this, getString(R.string.loading));
pd.show();
if (measureData != null) {
mMeasureList.set(pos, measureData);
}
getDairyLineApi().updateMeasureTooteet(mMeasureList.get(pos), new ResponseHandler() {
#Override
public void onSuccess(int statusCode, String content) {
dismiss();
AlertDialog.Builder builder = AlertUtils.getBuilder(FeedMeasureDetailsActivity.this);
builder.setMessage(R.string.updated_successfully);
builder.setPositiveButton(R.string.ok_caps, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (measureData != null) {
mMeasureList.set(pos, measureData);
tooteet.setMeasureJson(Measure.getMeasureDetailJSON(mMeasureList));
mTooteetManager.updateMeasureTooteet(tooteet, tooteet.getId());
mActionToSend = ACTION_MEASURE_UPDATE;
if (measureData.getValue() % 1 == 0) {
txtValues.setText("" + (int) measureData.getValue()+ " "+MeasureTypeSelector.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
} else {
txtValues.setText("" + measureData.getValue()+ " "+ MeasureTypeSelector
.getMeasureTypeById(FeedMeasureDetailsActivity.this, measureData.getMeasureTypeId()));
}
Log.d("TAG", "measureData.getStartDate(): "+measureData.getStartDate());
if(!TextUtils.isEmpty(measureData.getStartDate()) && !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrStartLayout.setVisibility(View.VISIBLE);
txtStartDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getStartDate(), "MMMM dd, yyyy hh:mm a"));
}
else{
lnrStartLayout.setVisibility(View.GONE);
}
Log.d("TAG", "measureData.getEndDate(): "+measureData.getEndDate());
if(!TextUtils.isEmpty(measureData.getEndDate())&& !measureData.getStartDate().equalsIgnoreCase("-1")) {
lnrEndLayout.setVisibility(View.VISIBLE);
txtEndDateTime.setText("" + DateConversion.getDateAndTimeWithoutGMT(measureData.getEndDate(), "MMMM dd, yyyy hh:mm a"));
}else{
lnrEndLayout.setVisibility(View.GONE);
}
if(!TextUtils.isEmpty(measureData.getDescription())){
lnrDescription.setVisibility(View.VISIBLE);
txtDescription.setText(measureData.getDescription());
}
else{
lnrDescription.setVisibility(View.GONE);
}
}
}
});
builder.create().show();
}
#Override
public void onFailure(int statusCode, String content) {
dismiss();
if (!TextUtils.isEmpty(content)) {
AlertUtils.showAlert(FeedMeasureDetailsActivity.this, content);
}
}
private void dismiss() {
if (pd != null && !isFinishing()) {
pd.dismiss();
}
}
});
}
#Override
public void onCancel() {
}
});
}
});
imgEdit.setTag(position);
imgDelete.setTag(position);
addView(parent);
}
My log inside addMeasureView is below:
adding measure data value ________________11111.0 position __________0
adding measure data value ________________22222.0 position __________1
But when i'm viewing this it in layout as this order
adding measure data value ________________22222.0
adding measure data value ________________11111.0
Please suggest me any idea.
This is my model class I'm using for getValue()
import com.kwypesoft.lanes.create_tooteet.LocalTooteetCreator;
import com.kwypesoft.lanes.utils.DateConversion;
import com.kwypesoft.lanes.utils.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.ArrayList;
public class Measure implements Serializable{
// "id": "398627f1-9392-4b3f-8741-903fbcbbd3be",
// "tooteetId": "ab36f69e-a0c8-4f31-aa8d-9b4038a76d57",
// "laneId": "00000000-0000-0000-0000-000000000000",
// "startDate": "2016-04-26T08:00:00",
// "endDate": "2016-04-27T10:00:00",
// "value": 125.6500000000000,
// "measureTypeId": 20
public String id;
public String tooteetId;
public String laneId;
public String startDate;
public String endDate;
public String description;
public double value;
public int measureTypeId;
public boolean isTimeSet;
public Measure() {
}
public Measure(JSONArray jsonArray) {
try {
for(int i =0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
id = jsonObject.optString("id");
tooteetId = jsonObject.optString("tooteetId");
laneId = jsonObject.optString("laneId");
startDate = jsonObject.optString("startDate");
endDate = jsonObject.optString("endDate");
description = jsonObject.optString("text");
value = jsonObject.optDouble("value");
measureTypeId = jsonObject.optInt("measureTypeId");
isTimeSet = jsonObject.optBoolean("isTimeSet");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String getMeasureJSON(ArrayList<LocalTooteetCreator.MeasureData> data) {
JSONArray jsonArray = new JSONArray();
for (LocalTooteetCreator.MeasureData items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", items.value);
jsonObject.put("text", items.description);
jsonObject.put("measureTypeId", items.measureTypeId);
if(items.startDate != -1){
jsonObject.put("startDate", DateConversion.getDateWithTFromMilliSeconds(items.startTime, items.startDate));
}
if(items.endDate != -1){
jsonObject.put("endDate", DateConversion.getDateWithTFromMilliSeconds(items.endTime, items.endDate));
}
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public static String getMeasureDetailJSON(ArrayList<Measure> data) {
JSONArray jsonArray = new JSONArray();
for (Measure items : data) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", items.id);
jsonObject.put("tooteetId", items.tooteetId);
jsonObject.put("laneId", items.laneId);
if(!TextUtils.isEmpty(items.startDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("startDate", items.startDate);
}
if(!TextUtils.isEmpty(items.endDate) && !items.getStartDate().equalsIgnoreCase("-1")){
jsonObject.put("endDate", items.endDate);
}
jsonObject.put("text", items.description);
jsonObject.put("value", items.value);
jsonObject.put("measureTypeId", items.measureTypeId);
jsonObject.put("isTimeSet", items.isTimeSet);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray.toString();
}
public String getId() {
return id;
}
public String getTooteetId() {
return tooteetId;
}
public String getLaneId() {
return laneId;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public double getValue() {
return value;
}
public int getMeasureTypeId() {
return measureTypeId;
}
public boolean getIsTimeSet() {
return isTimeSet;
}
public String getDescription() {
return description;
}
public boolean isTimeSet() {
return isTimeSet;
}
}
Hi I have done a mistake in addview method. Before my addview method is
mDisplayContainer.addView(view, mDisplayContainer.getChildCount() - 1);
Now i changed
mDisplayContainer.addView(view);
Its Working for me. Thank u so much for your comments

Adapter not showing data obtained from Parse.com through AsyncTask

I am trying to obtain some data from Parse.com through an AsyncTaskRunner. ANd then I intend to show them in a ListView. My custom adapter code is attached below :
public class ParseObjectAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ParseObject> parseArray;
DBShoppingHelper mydb2;
public ParseObjectAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
parseArray = new ArrayList<>();
}
#Override
public int getCount() {
try {
return parseArray.size();
}
catch (Exception e){
return 0;
}
}
#Override
public ParseObject getItem(int position) { return parseArray.get(position); }
#Override
public long getItemId(int position) {
return position;
}
public String getObjectId(int position){
return getItem(position).getObjectId();
}
public void sortByExpiry()
{
Comparator<ParseObject> comparator = new Comparator<ParseObject>() {
#Override
public int compare(ParseObject lhs, ParseObject rhs) {
return ((Integer) lhs.getInt("expiresIn")).compareTo(rhs.getInt("expiresIn"));
}
};
Collections.sort(parseArray, comparator);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
holder.shoppingListButton = (Button) convertView.findViewById(R.id.button_shopping);
// hang onto this holder for future recycling
convertView.setTag(holder);
int expiry = getItem(position).getInt("expiresIn");
if (expiry <= 0) {
holder.itemExpiryView.setTextColor(Color.rgb(255,80,54));
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
ParseObject p = getItem(position);
Intent goToAddItem = new Intent(mContext,ItemAddPage.class);
goToAddItem.putExtra("catg_passed", p.getString("category"));
goToAddItem.putExtra("update_flag", "YES");
goToAddItem.putExtra("name passed", p.getString("itemName"));
goToAddItem.putExtra("expires_in_passed", p.getString("expiresIn"));
goToAddItem.putExtra("price_passed", p.getString("itemPrice"));
mContext.startActivity(goToAddItem);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject p = getItem(position);
String android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
ParseQuery itemToBeDeleted = new ParseQuery("Items");
itemToBeDeleted.whereEqualTo("ACL", p.getACL());
itemToBeDeleted.whereEqualTo("objectId", p.getObjectId());
final Date deletionDate = new Date();
itemToBeDeleted.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
if (Items.size() == 1) {
ParseObject itemToDelete = Items.get(0);
itemToDelete.put("deleted", true);
itemToDelete.put("deletedOn", deletionDate);
itemToDelete.saveEventually();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
parseArray.remove(p);
sortByExpiry();
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
holder.shoppingListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
ParseObject p = getItem(position);
String add_to_list = p.getString("itemName");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String add_date = sdf.format(new Date());
System.out.println(add_date);
mydb2.insertItem(add_to_list, add_date);
Toast.makeText(mContext, "Item added to shopping list", Toast.LENGTH_SHORT).show();
}
});
ParseObject p = getItem(position);
String name2 = p.getString("itemName");
Integer ex = p.getInt("expiresIn");
String days_s ="";
if (ex == 0) {
days_s = "Expires today" ;
}
else if (ex == -1) {
days_s = "Expired yesterday";
}
else if (ex < 0) {
days_s = "Expired " + Math.abs(ex) + " days ago";
}
else if (ex == 1) {
days_s = "Expires tomorrow";
}
else {
days_s = "Expires in " + ex + " days";
}
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(days_s);
return convertView;
}
public void onClick(View v)
{
Intent viewItem = new Intent(v.getContext(), ItemAddPage.class);
v.getContext().startActivity(viewItem);
}
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
public Button shoppingListButton;
}
public void updateData(List<ParseObject> arrayPassed) {
// update the adapter's data set
parseArray = arrayPassed;
notifyDataSetChanged();
}
}
This is the method from which I am calling it..
public class WelcomeParse extends Activity {
ListView currentListView;
List<ParseObject> currentList;
ParseObjectAdapter itemAdder;
String catg;
DBShoppingHelper mydb2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
setContentView(R.layout.activity_main);
itemAdder = new ParseObjectAdapter(this, getLayoutInflater());
mydb2 = new DBShoppingHelper(this);
AsyncTaskAllItems runner = new AsyncTaskAllItems();
runner.execute();
// itemAdder.notifyDataSetChanged();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public class AsyncTaskAllItems extends AsyncTask<String, String, String> {
private String resp;
private Integer numItems = 0;
#Override
protected String doInBackground(String... params) {
try {
ParseQuery itemsAll = new ParseQuery("Items");
itemsAll.whereEqualTo("owner", ParseUser.getCurrentUser().getUsername());
// itemsByCategory.whereEqualTo("category", catg);
itemsAll.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
Log.d("owner", ParseUser.getCurrentUser().getUsername());
// HERE SIZE is 0 then 'No Data Found!'
numItems = Items.size();
if (numItems > 0) {
currentList = Items;
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
resp = "Done";
}
// catch (InterruptedException e) {
// e.printStackTrace();
// resp = e.getMessage();
// }
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
I do not get any error and the log correctly shows the number of items that should be retrieved. But the view does not get updated with the relevant data.
COuld anyone please show me where I am wrong? Anything else you need, just let me know. Much appreciated.
Try after replacing
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
With
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
currentListView.setAdapter(itemAdder);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
}

Categories

Resources