Android RecycleView adapter sometime doesnt call - android

I have an issue in RecycleView. My screen has two tabs, both tabs contain recycleview.It call normally most of the time but sometimes give empty screen. Just I wrote log & system.out and found this issue. I will paste my adapter class code here.
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
List<ContentTitle> titles;
Context context;
private List<Item> titleData = new ArrayList<Item>();
public ExpandableListAdapter(List<Item> data) {
this.titleData = data;
System.out.println("===this.titleData===" + this.titleData.size());
}
public void replaceContentFragment(String title,int id,int bookmarked) {
try {
SkillsApp SkillsApp = (SkillsApp) context.getApplicationContext();
Fragment fragment = new ContentActivityFragment();
FragmentManager fragmentManager = skillsUSAApp.mainActivity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
SkillsApp.subtitleID = id;
SkillsApp.isbookmark = (bookmarked == 0)? false:true;
SkillsApp.mainActivity.getSupportActionBar().setTitle(title);
SkillsApp.selectedSubtitleID = id;
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
try{
context = parent.getContext();
final SkillsApp skillsApp = (SkillsAApp)context.getApplicationContext();
if(!skillsApp.isDrawer){
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.main_title, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.sub_title, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("Child", "child");
TextView text = (TextView) view.findViewById(R.id.header_title);
}
});
return new RecyclerView.ViewHolder(view) {
};
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try{
System.out.println("==========##########");
final Item item = titleData.get(position);
final SkillsAApp skillsAApp = (SkillsAApp)context.getApplicationContext();
System.out.println("===onBindViewHolder item===" + item.mainTitle.title);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.mainTitle.title);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
}
itemController.layoutItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
if(!skillsAApp.isDrawer){
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<Item>();
int count = 0;
int pos = titleData.indexOf(itemController.refferalItem);
while (titleData.size() > pos + 1 && titleData.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(titleData.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.right_filled_arrow);
} else {
int pos = titleData.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
titleData.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
notifyDataSetChanged();
itemController.btn_expand_toggle.setImageResource(R.drawable.down_arrow);
item.invisibleChildren = null;
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
case CHILD:
View itemTextView = (View) holder.itemView;
TextView view = (TextView) itemTextView.findViewById(R.id.header_title);
view.setText(titleData.get(position).subtitle.title);
final int pos = position;
itemTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(!skillsUSAApp.isDrawer){
TextView text = (TextView) view.findViewById(R.id.header_title);
FlurryAgent.logEvent("Sub Category Item");
replaceContentFragment(text.getText().toString(), titleData.get(pos).subtitle.subtitleId, titleData.get(pos).subtitle.bookMarked);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public int getItemViewType(int position) {
return titleData.get(position).type;
}
#Override
public int getItemCount() {
return titleData.size();
}
#Override
public long getItemId(int position) {
return position;
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public RelativeLayout layoutItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
try{
header_title = (TextView) itemView.findViewById(R.id.header_title);
btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
layoutItem = (RelativeLayout) itemView.findViewById(R.id.ll_title);
}catch (Exception e){
e.printStackTrace();
}
}
}
public static class Item {
public int type;
public String text;
public ContentTitle mainTitle;
public ContentSubTitle subtitle;
public List<Item> invisibleChildren;
public Item(int type, String text, List<Item> children) {
this.type = type;
this.text = text;
this.invisibleChildren = children;
}
public Item(int type, ContentTitle title,ContentSubTitle stitle) {
this.type = type;
this.mainTitle = title;
this.subtitle=stitle;
}
public Item(int type, String text) {
this.type = type;
this.text = text;
}
}
}
Here is a calling adapter from tab fragment
recyclerview = (RecyclerView) v.findViewById(R.id.recyclerview);
recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false));
// recyclerview.setLayoutManager(new LinearLayoutManager(v.getContext()));
ExpandableListAdapter adapter = new ExpandableListAdapter(items);
recyclerview.setAdapter(adapter);
adapter.notifyDataSetChanged();
could you please advice me what is an issue? I didn't get any console error message.Could you please help me anyone here

Related

How to disable previous items in a ListView

I am trying to develop an activity where there is a custom listView made out of CustomAdapter.
The list consists of a TextView and an EditText. The EditText when clicked, it auto fetches the system time.
What I want is when a particular EditText is filled, I want all the previous(above) list items in the sequence to be disabled.
So far, I have tried using isEnabled() and areAllItemsEnabled() functions returning respective boolean values using position, but however didn’t work.
Please help me achieve the above.
Thanks.
This is my CustomAdapter Class
public class SelectStnListByRoute extends BaseAdapter implements View.OnClickListener {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if(position==position){
return false;
}
return false;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position)); //Here I am getting the position of the row item clicked, where should I put the Onclick false for disabling all of the above fields using the position?
}
});
viewHolder.txtStnDep.setOnClickListener(this);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
int ref;
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case txtArrivalTime:
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
textViewArrVal.setClickable(false);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
break;
case txtDepTime:
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
break;
default:
break;
}
}
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
You can do this as below mentioned -:
You need to store the position of clicked button was. So initialize a variable in your class
int mButtonSelected = -1;
EDIT 1.
Then make a change to your isEnabled method
#Override
public boolean isEnabled(int position) {
if(position<mButtonSelected){
return false;
}
return true;
}
That will work it if any other button was clicked. but you have to do that in your onClick
mButtonSelected = position;
notifyDataSetChanged();
Let me it worked or not
EDIT
see below changes in your code-:
public class SelectStnListByRoute extends BaseAdapter {
Context context;
ArrayList<StnNames> stnList;
LayoutInflater layoutInflater = null;
ViewHolder viewHolder;
private int mLastClicked;
private SQLiteDB sqLiteDB;
int mArrivalSelected = -1;
int mDepartSelected = -1;
public SelectStnListByRoute(Context context, ArrayList<StnNames> stnList) {
super();
this.context = context;
this.stnList = stnList;
layoutInflater = LayoutInflater.from(context);
sqLiteDB = new SQLiteDB(context);
}
#Override
public int getCount() {
return stnList.size();
}
#Override
public Object getItem(int position) {
return stnList.get(position);
}
#Override
public long getItemId(int position) {
return stnList.indexOf(getItem(position));
}
public int getViewTypeCount() {
return 1;
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (position <= mArrivalSelected) {
return false;
}
return true;
}
public boolean isEnabledd(int position) {
if (position <= mDepartSelected) {
return false;
}
return true;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
int type = getItemViewType(position);
StnNames stnDetails = stnList.get(position);
viewHolder = new ViewHolder();
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.footplate_custome_layout, null);
viewHolder.txtStnNAme = (TextView) convertView.findViewById(R.id.txtStnCode);
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
viewHolder.txtStnDep = (TextView) convertView.findViewById(R.id.txtDepTime);
convertView.setTag(viewHolder);
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
} else {
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.txtStnArr.setTag(stnDetails);
viewHolder.txtStnDep.setTag(stnDetails);
}
viewHolder.txtStnNAme.setText(stnDetails.getStnCode());
if (!isEnabled(position)) {
if (position <= mArrivalSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
if (position < mArrivalSelected) {
viewHolder.txtStnDep.setEnabled(false);
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mArrivalSelected = position;
arrivalClick(view);
notifyDataSetChanged();
}
});
if (!isEnabledd(position)) {
if (position <= mDepartSelected) {
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#ffa500"));
viewHolder.txtStnArr.setEnabled(false);
viewHolder.txtStnDep.setEnabled(false);
} else {
viewHolder.txtStnArr.setEnabled(true);
viewHolder.txtStnDep.setEnabled(true);
viewHolder.txtStnArr.setBackgroundColor(Color.parseColor("#b4b4b4"));
viewHolder.txtStnDep.setBackgroundColor(Color.parseColor("#b4b4b4"));
}
}
viewHolder.txtStnDep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: ", String.valueOf(position));
mDepartSelected = position;
departureClick(view);
notifyDataSetChanged();
}
});
viewHolder.txtStnArr = (TextView) convertView.findViewById(R.id.txtArrivalTime);
if (stnDetails.getArrivalTime() != null) {
viewHolder.txtStnArr.setText(stnDetails.getArrivalTime());
} else {
viewHolder.txtStnArr.setText("");
}
if (stnDetails.getDeptTime() != null) {
viewHolder.txtStnDep.setText(stnDetails.getDeptTime());
} else {
viewHolder.txtStnDep.setText("");
}
return convertView;
}
class ViewHolder {
TextView txtStnNAme, txtStnArr, txtStnDep;
StnNames pos;
int ref;
}
public void arrivalClick(View view) {
TextView textViewArrVal = (TextView) view.findViewById(R.id.txtArrivalTime);
StnNames listItemsArrr = (StnNames) textViewArrVal.getTag();
if (listItemsArrr.getArrivalTime() != getCurrentTime()) {
listItemsArrr.setArrivalTime(getCurrentTime());
int stnId = listItemsArrr.getStnId();
String arrClick = "arrival";
String upSideKm = listItemsArrr.getStnUpsideKm();
String downsideKm = listItemsArrr.getStnDownSideKm();
String arrTime = getCurrentTime();
/* sqLiteDB.open();
*//* long abc = sqLiteDB.insertJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick);*//*
*//* long abcd = sqLiteDB.updateJourneySchedule(stnId,arrTime,"",userId,journeyId,latitute,longitute,journyDate,arrClick,downsideKm,upSideKm);
Log.e("arrclick",String.valueOf(abcd));*//*
sqLiteDB.close();*/
if (listItemsArrr.getArrivalTime() != null) {
int position = textViewArrVal.getSelectionStart();
textViewArrVal.setText(listItemsArrr.getArrivalTime());
} else {
textViewArrVal.setText("");
}
}
}
public void departureClick(View view) {
TextView textViewDepVal = (TextView) view.findViewById(R.id.txtDepTime);
StnNames listItemsDepp = (StnNames) textViewDepVal.getTag();
if (listItemsDepp.getDeptTime() != getCurrentTime()) {
listItemsDepp.setDeptTime(getCurrentTime());
String depTime = getCurrentTime();
int stnId = listItemsDepp.getStnId();
String depClick = "departure";
String upSideKm = listItemsDepp.getStnUpsideKm();
String downsideKm = listItemsDepp.getStnDownSideKm();
sqLiteDB.open();
/*long abc = sqLiteDB.insertJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick);*/
/*long abcd = sqLiteDB.updateJourneySchedule(stnId,"",depTime,userId,journeyId,latitute,longitute,journyDate,depClick,downsideKm,upSideKm);
Log.e("depclick",String.valueOf(abcd));*/
sqLiteDB.close();
if (listItemsDepp.getDeptTime() != null) {
textViewDepVal.setText(listItemsDepp.getDeptTime());
} else {
textViewDepVal.setText("");
}
}
}
public String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HH:mm:ss");
String arrDate = mdformat.format(calendar.getTime());
return arrDate;
}
}
Get the position of the row which is clicked and then set onclick false for positions less than clicked position
as follows:
viewHolder.txtStnArr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("Position: " , String.valueOf(position));
for (int i = 0; i < position; i++) {
viewHolder.txtStnArr.setEnable(false);
}
notifyDataSetChanged();
}
});

RecyclerView use so much memory until OOM

"Memory" rose quickly after open the Fragment that contains RecyclerView.When scorll up and down several times,"memory" continue to rise,and then show OOM and Force Close.
The following is the RecyclerView screenshot:
The following is my Adapter code:
I just use one RecyclerView the full page and nested a GridView at the first item;
public class CategoryPagerItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//热门分类
public static final int VIEW_TYPE_HOT_SUB_CATE = 1;
//banner+商品横滑推荐
public static final int VIEW_TYPE_PROMOTION_LIST = 2;
public static final int VIEW_TYPE_PROMOTION_LIST_LABEL = 3;
//商品集合
public static final int VIEW_TYPE_GOODS_LIST = 4;
//商品集合标签
public static final int VIEW_TYPE_GOODS_LIST_LABEL = 5;
//加载更多
public static final int VIEW_TYPE_GOODS_LIST_MORE = 6;
public static final int COUNT_HOT_SUB_CATE=1;
public static final int COUNT_HOT_GOODS_LIST_LABEL=1;
public static final int COUNT_HOT_GOODS_LIST_MORE=1;
private String mTagId;//TabLayout的title对应的tagid
private String mTitleName;//TabLayout的title对应的name
private int mIndex = -1;//ViewPager的index
private int mLevel = 1;//级别分类
private Context mContext;
//相关的banner+横滑商品
private ArrayList<CategoryList.RelatedTagListEntity> mRelatedTagListEntityList;
//热门分类
private ArrayList<CategoryList.HotSubCategoryListEntity> mHotSubCategoryListEntityList;
//商品列表
private ArrayList<CategoryList.GoodListEntity> mGoodListEntityList;
private int mRelatedTagSize, mGoodsListSize;
private OnGoodsItemClickListener mOnGoodsItemClickListener;
public CategoryPagerItemAdapter(Context context, String tagId, String titleName, int index) {
mTagId = tagId;
mTitleName = titleName;
mIndex = index;
mContext = context;
}
public void resetData(ArrayList<CategoryList.HotSubCategoryListEntity> hotSubCategoryListEntityList,
ArrayList<CategoryList.RelatedTagListEntity> relatedTagListEntityList,
ArrayList<CategoryList.GoodListEntity> goodListEntityList, int level) {
mHotSubCategoryListEntityList = hotSubCategoryListEntityList;
mRelatedTagListEntityList = relatedTagListEntityList;
mGoodListEntityList = goodListEntityList;
mRelatedTagSize = mRelatedTagListEntityList == null ? 0 : mRelatedTagListEntityList.size();
mGoodsListSize = mGoodListEntityList == null ? 0 : mGoodListEntityList.size();
mLevel = level;
notifyDataSetChanged();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
//头部的十个分类
if (viewType == VIEW_TYPE_HOT_SUB_CATE) {
return new HotSubCateViewHolder(layoutInflater.inflate(R.layout.category_classify_item_hot_sub_cate, parent, false));
} else if (viewType == VIEW_TYPE_PROMOTION_LIST) {//banner+商品横滑推荐
return new PromotionViewHolder(layoutInflater.inflate(R.layout.category_classify_item_related, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST) {//商品列表
return new GoodListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_LABEL) {
return new GoodListLabelViewHolder(layoutInflater.inflate(R.layout.category_classify_item_goods_list_label, parent, false));
} else if (viewType == VIEW_TYPE_GOODS_LIST_MORE) {//更多
return new MoreGoodsListViewHolder(layoutInflater.inflate(R.layout.category_classify_item_more, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder vh, final int position) {
switch (vh.getItemViewType()) {
//热门分类
case VIEW_TYPE_HOT_SUB_CATE:
final HotSubCateViewHolder hotSubCateHolder = (HotSubCateViewHolder) vh;
int horizontalSpacing = (UJiPin.SCREEN_WIDTH - UDensity.dip2px(mContext, 16) * 2 - UDensity.dip2px(mContext, 50) * 5) / 4;
hotSubCateHolder.mGridview.setHorizontalSpacing(horizontalSpacing);
hotSubCateHolder.mGridview.setVerticalSpacing(UDensity.dip2px(mContext, 20));
final CategoryHotSubCateAdapter categoryHotSubCateAdapter = new CategoryHotSubCateAdapter(mContext, mHotSubCategoryListEntityList);
hotSubCateHolder.mGridview.setAdapter(categoryHotSubCateAdapter);
hotSubCateHolder.mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int hotSubViewType = categoryHotSubCateAdapter.getItemViewType(pos);
CategoryList.HotSubCategoryListEntity hotSubCategoryListEntity = mHotSubCategoryListEntityList.get(pos);
if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE) {//热门分类
JumpUtils.JumpClassifyList((BaseActivity) mContext, hotSubCategoryListEntity.getLevel(), hotSubCategoryListEntity.getTag_id(), hotSubCategoryListEntity.getName());
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(hotSubCategoryListEntity.getName()),
"class-1-" + UString.urlEncode(hotSubCategoryListEntity.getName()));
} else if (hotSubViewType == CategoryHotSubCateAdapter.VIEW_TYPE_HOT_SUB_CATE_MORE) {//点击more
Intent intent = new Intent(mContext, CategoryPagerMoreActivity.class);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_NAME, mTitleName);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_INT_CATEGORY_INDEX, mIndex);
intent.putExtra(CategoryPagerMoreActivity.EXTRA_STRING_CATEGORY_TAG_ID, mTagId);
mContext.startActivity(intent);
UJPTrack.getInstance().setTrack((BaseActivity) mContext,
UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName),
"class-1-more");
}
}
});
break;
case VIEW_TYPE_PROMOTION_LIST://banner+横滑
PromotionViewHolder promotionViewHolder = (PromotionViewHolder) vh;
final int promotionPosition = position - COUNT_HOT_SUB_CATE;
//防止recyclerview复用出现错乱的办法是有if必须有else,并且处理相反
GridLayoutManager.LayoutParams promotionLP = (GridLayoutManager.LayoutParams) promotionViewHolder.mContainer.getLayoutParams();
if (promotionPosition == 0) {//如果是第一个,则显示“相关推荐“
promotionViewHolder.mLabel.setVisibility(View.VISIBLE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 16), -UDensity.dip2px(mContext, 5), 0);
} else {
promotionViewHolder.mLabel.setVisibility(View.GONE);
promotionLP.setMargins(-UDensity.dip2px(mContext, 5), UDensity.dip2px(mContext, 4), -UDensity.dip2px(mContext, 5), 0);
}
promotionViewHolder.mContainer.setLayoutParams(promotionLP);
final CategoryList.RelatedTagListEntity relatedTagListEntity = mRelatedTagListEntityList.get(promotionPosition);
FrescoImageLoader.getInstance().load(promotionViewHolder.mCover, relatedTagListEntity.getCover());
//点击banner
promotionViewHolder.mCover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), null, promotionPosition);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_LABEL_ + UString.urlEncode(relatedTagListEntity.getName()),
"class-2-" + covertInt(promotionPosition + 1));
}
});
final CategoryChoiceTagAdapter adapter = new CategoryChoiceTagAdapter(mContext);
//点击横滑商品
adapter.setOnItemClickListener(new CategoryChoiceTagAdapter.OnItemClickListener() {
#Override
public void onTag4ItemClick(final CategoryList.GoodListEntity goodListEntity, int position, View view) {
Jumper.newJumper().putString(GoodsDetailActivity.EXTRA_STRING_GOODID, goodListEntity.getGoods_id() + "")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCENAME, "分类")
.putString(GoodsDetailActivity.EXTRA_STRING_SOURCEID, "活动横滑")
.jump((BaseActivity) mContext, GoodsDetailActivity.class);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_GOOD + goodListEntity.getGoods_id(),
"class-2-" + covertInt(promotionPosition + 1));
}
});
promotionViewHolder.mSlideMoreRecycleView.setAdapter(adapter);
adapter.setDataRefresh(relatedTagListEntity.getGoods_list());
//横滑
promotionViewHolder.mSlideMoreRecycleView.setOnSlideTwiceLisner(new SlideMoreRecycleView.SlideTwiceLisner() {
#Override
public void onSliding(RecyclerView recyclerView) {
JumpUtils.JumpActivityTopic((BaseActivity) mContext, relatedTagListEntity.getName(),
relatedTagListEntity.getTag_id(), "", promotionPosition);
}
});
break;
case VIEW_TYPE_GOODS_LIST_LABEL://商品列表的label
break;
case VIEW_TYPE_GOODS_LIST://商品列表
int goodsListPosition = position - COUNT_HOT_SUB_CATE - mRelatedTagSize - COUNT_HOT_GOODS_LIST_LABEL;
final CategoryList.GoodListEntity goodListEntity = mGoodListEntityList.get(goodsListPosition);
final GoodListViewHolder goodsListHolder = (GoodListViewHolder) vh;
ViewCompat.setTransitionName(goodsListHolder.ivCover, mContext.getString(R.string.transition_name) + position);
goodsListHolder.rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnGoodsItemClickListener != null) {
mOnGoodsItemClickListener.onItemClick(goodsListHolder.rootView, goodListEntity, position, goodListEntity.getThumbnail());
}
}
});
goodsListHolder.tv_goods_selling_point.setText(goodListEntity.getSelling_point());
if (!TextUtils.isEmpty(goodListEntity.getThumbnail()))
FrescoImageLoader.getInstance().load(goodsListHolder.ivCover, goodListEntity.getThumbnail());
if (!TextUtils.isEmpty(goodListEntity.getMark())) {
goodsListHolder.ivGroupLogo.setVisibility(View.VISIBLE);
FrescoImageLoader.getInstance().load(goodsListHolder.ivGroupLogo, goodListEntity.getMark());
} else {
goodsListHolder.ivGroupLogo.setVisibility(View.GONE);
}
goodsListHolder.tvDescription.setText(goodListEntity.getGoods_name());
if (!TextUtils.isEmpty(goodListEntity.getGoods_price()))
goodsListHolder.tvPrice.setText(String.format(mContext.getString(R.string.rmb), goodListEntity.getGoods_price()));
//售罄
if (goodListEntity.getProduct_stock_total() <= 0)
goodsListHolder.ivSoldOut.setVisibility(View.VISIBLE);
else
goodsListHolder.ivSoldOut.setVisibility(View.GONE);
break;
case VIEW_TYPE_GOODS_LIST_MORE://更多推荐
MoreGoodsListViewHolder moreGoodsListViewHolder = (MoreGoodsListViewHolder) vh;
moreGoodsListViewHolder.mContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JumpUtils.JumpClassifyList((BaseActivity) mContext, mLevel, mTagId, mTitleName);
UJPTrack.getInstance().setTrack((BaseActivity) mContext, UJPTrack.PAGE_CLASS_ + UString.urlEncode(mTitleName), UJPTrack.PAGE_CLASS_CLASS + UString.urlEncode(mTitleName));
}
});
break;
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
return VIEW_TYPE_HOT_SUB_CATE;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize) {
return VIEW_TYPE_PROMOTION_LIST;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL) {
return VIEW_TYPE_GOODS_LIST_LABEL;
} else if (position < COUNT_HOT_SUB_CATE + mRelatedTagSize + COUNT_HOT_GOODS_LIST_LABEL + mGoodsListSize) {
return VIEW_TYPE_GOODS_LIST;
} else {
return VIEW_TYPE_GOODS_LIST_MORE;
}
}
#Override
public int getItemCount() {
return mGoodsListSize + mRelatedTagSize + COUNT_HOT_SUB_CATE +
COUNT_HOT_GOODS_LIST_LABEL + COUNT_HOT_GOODS_LIST_MORE;
}
//头部的热门分类
private static class HotSubCateViewHolder extends RecyclerView.ViewHolder {
private MyGridview mGridview;
HotSubCateViewHolder(View view) {
super(view);
mGridview = (MyGridview) view.findViewById(R.id.grid_view);
}
}
//banner+推荐横滑
private static class PromotionViewHolder extends RecyclerView.ViewHolder {
private SimpleDraweeView mCover;
private LinearLayout mContainer;
private TextView mLabel;
private SlideMoreRecycleView mSlideMoreRecycleView;
PromotionViewHolder(View view) {
super(view);
mContainer = (LinearLayout) view.findViewById(R.id.ll);
mLabel = (TextView) view.findViewById(R.id.label);
mCover = (SimpleDraweeView) view.findViewById(R.id.iv_cover);
mSlideMoreRecycleView = (SlideMoreRecycleView) view.findViewById(rv_tag_list);
}
}
//商品列表
private static class GoodListViewHolder extends RecyclerView.ViewHolder {
View rootView;
SimpleDraweeView ivCover;
TextView tvDescription;
TextView tvPrice;
TextView tv_goods_selling_point;
ImageView ivSoldOut;
SimpleDraweeView ivGroupLogo;
GoodListViewHolder(View v) {
super(v);
rootView = v;
ivCover = (SimpleDraweeView) v.findViewById(R.id.iv_cover);
tvDescription = (TextView) v.findViewById(R.id.tv_descrption);
tvPrice = (TextView) v.findViewById(R.id.tv_price);
tv_goods_selling_point = (TextView) v.findViewById(R.id.tv_goods_selling_point);
ivSoldOut = (ImageView) v.findViewById(R.id.iv_sold_out);
ivGroupLogo = (SimpleDraweeView) v.findViewById(R.id.iv_group_tag);
}
}
private static class GoodListLabelViewHolder extends RecyclerView.ViewHolder {
TextView mLabel;
public GoodListLabelViewHolder(View itemView) {
super(itemView);
mLabel = (TextView) itemView.findViewById(R.id.label);
}
}
private static class MoreGoodsListViewHolder extends RecyclerView.ViewHolder {
private LinearLayout mContainer;
MoreGoodsListViewHolder(View itemView) {
super(itemView);
mContainer = (LinearLayout) itemView.findViewById(R.id.container);
}
}
//点击双栏列表接口
public interface OnGoodsItemClickListener {
void onItemClick(View rootView, CategoryList.GoodListEntity goodListEntity, int position, String imageUrl);
}
public void addOnGoodsItemClickListener(OnGoodsItemClickListener listener) {
mOnGoodsItemClickListener = listener;
}
public String covertInt(int value) {
return value <= 9 ? ("0" + value) : value + "";
}

OutOfMemoryError ViewPager Activity

In one of activity contains RecyclerView in which certain items are rendered and on clicking any item its moving to another activity which is having a massive data from a server, its like a detail page of news along with images from server to render in its gallery section, using ViewPager along PagerAdapter(Some news articles may contains 20-30 images.
Whenever I move forward and backward from these activites my application crashes with OutOfMemory Error.
So far I have tried calling System.gc() and then finish() after moving back from detail activity to the one containing RecyclerView but still getting OutOfMemory errors.
I know its a memory leak as its getting large amount of data and then rendering at different places in activity but don't know how to handle it.
I have read some solutions mentioning android:largeHeap but it also doesn't guarentee that you may get large heap with some other cons like frequent pausings.
PagerAdapter:
public class SingleNewsGalleryAdapter extends PagerAdapter {
private String URL="some url";
Context mContext;
LayoutInflater mLayoutInflater;
List<String> newsList= Collections.emptyList();
int width=-1;
int heigth=-1;
public SingleNewsGalleryAdapter(Context context,List<String> newsList) {
this.newsList = newsList;
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return newsList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
final int pos = position;
View itemView = mLayoutInflater.inflate(R.layout.single_news_pager_layout, container, false);
final Holder holder = new Holder();
holder.imageView = (ImageView) itemView.findViewById(R.id.slidr_img);
holder.left = (ImageView) itemView.findViewById(R.id.swipe_left);
if(position==0){
holder.left.setColorFilter(ContextCompat.getColor(mContext, R.color.trans_black));
}
holder.right= (ImageView) itemView.findViewById(R.id.swipe_right);
if(position==(newsList.size()-1)){
holder.right.setColorFilter(ContextCompat.getColor(mContext, R.color.trans_black));
}
holder.left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos>0){
int desc = pos-1;
if(mContext instanceof SingleNewsActivity){
((SingleNewsActivity)mContext).changePage(desc);
}
}
}
});
holder.right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos<newsList.size()){
if(mContext instanceof SingleNewsActivity){
int inc = pos+1;
((SingleNewsActivity)mContext).changePage(inc);
//Toast.makeText(mContext,pos+"",Toast.LENGTH_LONG).show();
}
}
}
});
String news = newsList.get(position);
//imageView.setImageResource(newsList.get(position).getNews_photo());
int dpiCheck=0;
String res="";
switch (mContext.getResources().getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
dpiCheck=1;
break;
case DisplayMetrics.DENSITY_MEDIUM:
dpiCheck=2;
break;
case DisplayMetrics.DENSITY_HIGH:
dpiCheck=3;
break;
case DisplayMetrics.DENSITY_XHIGH:
dpiCheck=4;
break;
}
if(dpiCheck==3){
res="525x255x1-";
}
else if(dpiCheck==4){
res="700x340x1-";
}
// res = width+"x"+height+"x1-";
String url = URL+res+news;
Uri uri = Uri.parse(url);
Picasso.with(this.mContext).load(uri).into(holder.imageView);
container.addView(itemView);
return itemView;
}
#Override
public float getPageWidth(int position) {
return 1f;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout) object);
}
static class Holder {
ImageView imageView;
ImageView left;
ImageView right;
}
}
and my RecyclerAdapter from the listing activity:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
String URL = "some url";
List<News> newsList = Collections.emptyList();
Context ctx;
int layoutID;
public NewsAdapter(List<News> newsList, Context ctx, int layout) {
this.layoutID = layout;
this.newsList = newsList;
this.ctx = ctx;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(layoutID, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
News news = newsList.get(position);
String title = news.getNews_title();
holder.title.setText(title);
String desc = news.getNews_description();
String htmlDesc;
String formatedDesc =desc.substring(0, Math.min(desc.length(), 50))+"...";
if (Build.VERSION.SDK_INT >= 24) {
holder.desc.setText(Html.fromHtml(desc, Html.FROM_HTML_SEPARATOR_LINE_BREAK_DIV));
} else {
holder.desc.setText(Html.fromHtml(desc));
}
String authorName;
if(news.getAuthor().trim().equals("") || news.getAuthor()==null){
authorName="Anonymous";
}
else{
authorName = news.getAuthor().trim();
}
holder.author.setText(authorName);
//Format Date
SimpleDateFormat fromUser = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat myFormat = new SimpleDateFormat("d/M/yy");
String formatedDate="";
try {
formatedDate = myFormat.format(fromUser.parse(news.getNews_add_date()));
} catch (ParseException e) {
e.printStackTrace();
}
holder.date.setText(formatedDate);
//view counter format
Integer viewCount = Integer.parseInt(news.getViews());
DecimalFormat formatter = new DecimalFormat("##,##,###");
String number = formatter.format(viewCount);
holder.views.setText(number);
//comments counter format
Integer commentCount = Integer.parseInt(news.getComments());
formatter = new DecimalFormat("##,##,###");
String c_number = formatter.format(commentCount);
holder.comments.setText(c_number);
int dpiCheck=0;
String res="";
switch (ctx.getResources().getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
dpiCheck=1;
break;
case DisplayMetrics.DENSITY_MEDIUM:
dpiCheck=2;
break;
case DisplayMetrics.DENSITY_HIGH:
dpiCheck=3;
break;
case DisplayMetrics.DENSITY_XHIGH:
dpiCheck=4;
break;
}
if(dpiCheck==3){
res="165x165x1-";
}
else if(dpiCheck==4){
res="220x220x1-";
}
String url = URL+res+news.getNews_photo();
Uri uri = Uri.parse(url);
Picasso.with(this.ctx).load(uri).into(holder.image);
}
#Override
public int getItemCount() {
return newsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title,desc,date,views,comments,author;
ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView)view.findViewById(R.id.news_title);
author = (TextView)view.findViewById(R.id.author);
desc =(TextView)view.findViewById(R.id.news_desc);
date=(TextView)view.findViewById(R.id.date);
views = (TextView)view.findViewById(R.id.view_counter);
comments = (TextView)view.findViewById(R.id.comment_counter);
image = (ImageView) view.findViewById(R.id.news_img);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id="";
String cat="";
String brand="";
if(Build.VERSION.SDK_INT>=24){
id= newsList.get(getAdapterPosition()).getNews_id();
cat = newsList.get(getAdapterPosition()).getCat_id();
brand = newsList.get(getAdapterPosition()).getBrand_id();
}
else{
id= newsList.get(getPosition()).getNews_id();
cat = newsList.get(getPosition()).getCat_id();
brand = newsList.get(getPosition()).getBrand_id();
}
Intent intent = new Intent(view.getContext(), SingleNewsActivity.class);
intent.putExtra("NEWSID",id);
intent.putExtra("NEWSCAT",cat);
intent.putExtra("NEWSBRAND",brand);
ctx.startActivity(intent);
// Toast.makeText(view.getContext(), "position = " + id, Toast.LENGTH_SHORT).show();
}
});
}
}
public void setFilter(List<News> newList){
this.newsList = new ArrayList<>();
this.newsList.addAll(newList);
notifyDataSetChanged();
}
public void loadMore(List<News> newList){
this.newsList.addAll(newList);
notifyDataSetChanged();
}
}
The Error Statement OutOfMemory Error at NewsAdapter.onCreateViewHolder(NewsAdapter.java:49)
where the onCreateViewHolder is called.

How to update the value of the textview inside the fragment on the click of the button present in the adapter class in android?

I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.

ListView with different layouts with two different objects

I want to populate a ListView with different layouts for odd and even rows. It should look like this:
I use two objects "OddListItem" and "EvenListItem" to store/access the data. I do not know how to pass both objects to my custom listview adapter and get the correct view.
My object classes:
public class OddListItem {
private String time_start;
private String time_end;
private String location;
public OddListItem(String time_start, String time_end, String location) {
super();
this.time_start = time_start;
this.time_end = time_end;
this.location = location;
}
// getters and setters
void setTimeStart(String time_start) {
this.time_start = time_start;
}
void setTimeEnd(String time_end) {
this.time_end = time_end;
}
void setLocation(String location) {
this.location = location;
}
public String getTimeStart() {
return time_start;
}
public String getTimeEnd() {
return time_end;
}
public String getLocation() {
return location;
}
}
public class EvenListItem {
private String image;
private String location;
public EvenListItem (String image, String location) {
super();
this.image = image;
this.location = location;
}
// getters and setters
void setImage(String image) {
this.image = image;
}
void setLocation(String location) {
this.location = location;
}
public String getImage() {
return image;
}
public String getLocation() {
return location;
}
}
MyCustomAdapter:
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<OddListItem> mData = new ArrayList<OddListItem>();
private LayoutInflater mInflater;
//private TreeSet mSeparatorsSet = new TreeSet();
private Context context;
public MyCustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public void addItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
public void addSeparatorItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
/*if ((position%2) == 0){
type = TYPE_ITEM;
} else {
type = TYPE_SEPARATOR;
}
return type;*/
return position%2;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OddListItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
//fill the layout with values
/*holder.tv_time_from.setText("12:34");
holder.tv_time_to.setText("12:37");
holder.tv_current_location_odd.setText("Aktueller Standort");*/
holder.tv_time_from.setText(mData.get(position).getTimeStart());
holder.tv_time_to.setText(mData.get(position).getTimeEnd());
holder.tv_current_location_odd.setText(mData.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText("Hauptbahnhof");
holder.img_transport.setImageDrawable(context.getResources().getDrawable(R.drawable.rollator));
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
}
Here I generate the data and call the adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_connection);
generateData();
//fill ListView with custom content from MyCustomAdapter class
mAdapter = new MyCustomAdapter(getApplicationContext());
for (int i = 1; i < odd_items.size(); i++) {
mAdapter.addItem(odd_items.get(i));
if (i % 1 == 0) {
mAdapter.addSeparatorItem(odd_items.get(i));
}
}
setListAdapter(mAdapter);
//set duration text
tv_duration = (TextView)findViewById(R.id.tv_duration);
tv_duration.setText("Dauer: 22 Minuten");
}
private void generateData() {
odd_items = new ArrayList<OddListItem>();
odd_items.add(new OddListItem("12:34", "", "Aktueller Standort"));
odd_items.add(new OddListItem("12:37", "12:37", "TUM"));
odd_items.add(new OddListItem("12:42", "12:42", "Hauptbahnhof Nord"));
odd_items.add(new OddListItem("12:48", "12:48", "Hauptbahnhof"));
even_items = new ArrayList<EvenListItem>();
even_items.add(new EvenListItem("R.drawable.rollator", "3 Minuten Fußweg"));
even_items.add(new EvenListItem("R.drawable.bus", "Richtung Hauptbahnhof Nord"));
even_items.add(new EvenListItem("R.drawable.rollator", "6 Minuten Fußweg"));
mData = new Data(odd_items, even_items);
}
Any help would be great. Maybe there is also a better approach then please let me know.
I would create a Single list of Items
public class Items {
private String time_start;
private String time_end;
private String location;
private int image;
private String locationeven;
private int oddoreven;
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLocationeven() {
return locationeven;
}
public void setLocationeven(String locationeven) {
this.locationeven = locationeven;
}
public int getOddoreven() {
return oddoreven;
}
public void setOddoreven(int oddoreven) {
this.oddoreven = oddoreven;
}
}
In onCreate of Activity call
generateData() ;
Then
ArrayList<Items> oddorevenlist = new ArrayList<Items>();
private void generateData() {
Items item1 = new Items();
item1.setTime_start("12:34");
item1.setTime_end("");
item1.setLocation("Aktueller Standort");
item1.setOddoreven(0);
oddorevenlist.add(item1);
Items item2 = new Items();
item2.setImage(R.drawable.ic_launcher);
item2.setLocationeven("3 Minuten Fußweg");
item2.setOddoreven(1);
oddorevenlist.add(item2);
Items item3 = new Items();
item3.setTime_start("12:37");
item3.setTime_end("12:37");
item3.setLocation("Tum");
item3.setOddoreven(0);
oddorevenlist.add(item3);
Items item4 = new Items();
item4.setImage(R.drawable.ic_launcher);
item4.setLocationeven("Richtung Hauptbahnhof Nord");
item4.setOddoreven(1);
oddorevenlist.add(item4);
Items item5 = new Items();
item5.setTime_start("12:42");
item5.setTime_end("12:42");
item5.setLocation("Hauptbahnhof Nord");
item5.setOddoreven(0);
oddorevenlist.add(item5);
Items item6 = new Items();
item6.setImage(R.drawable.ic_launcher);
item6.setLocationeven("R6 Minuten Fußweg");
item6.setOddoreven(1);
oddorevenlist.add(item6);
Items item7 = new Items();
item7.setTime_start("12:48");
item7.setTime_end("12:48");
item7.setLocation("HHauptbahnhof");
item7.setOddoreven(0);
oddorevenlist.add(item7);
MyCustomAdapter mAdapter = new MyCustomAdapter(this,oddorevenlist);
setListAdapter(mAdapter);
}
Adapter code
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Items> oddorevenlist ;
private LayoutInflater mInflater;
private Context context;
public MyCustomAdapter(Context context, ArrayList<Items> oddorevenlist) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.oddorevenlist = oddorevenlist;
}
#Override
public int getItemViewType(int position) {
if (oddorevenlist.get(position).getOddoreven()==0){
type = TYPE_ITEM;
} else if (oddorevenlist.get(position).getOddoreven()==1) {
type = TYPE_SEPARATOR;
}
return type;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return oddorevenlist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
holder.tv_time_from.setText(oddorevenlist.get(position).getTime_start());
holder.tv_time_to.setText(oddorevenlist.get(position).getTime_end());
holder.tv_current_location_odd.setText(oddorevenlist.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText(oddorevenlist.get(position).getLocationeven());
holder.img_transport.setImageResource(R.drawable.ic_launcher);
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
}
Snap

Categories

Resources