0

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.

Mehvish Ali
  • 622
  • 1
  • 9
  • 26
  • Try using glide it might solve your problem – Nitesh Dec 09 '16 at 18:35
  • @Nitesh Ive tried it with glide as well but of no use – Mehvish Ali Dec 09 '16 at 19:06
  • is this the line? Picasso.with(this.mContext).load(uri).into(holder.imageView); – Mushirih Dec 09 '16 at 19:15
  • @PeterMushirih nope its crashing where the inflator is inflating the layout in `RecyclerView Adapter` – Mehvish Ali Dec 09 '16 at 19:18
  • have you tried View view = LayoutInflater.from(ctx) .inflate(layoutID, parent, false); – Mushirih Dec 09 '16 at 19:24
  • I think thats not the issue with it. either you get it by context or parent context. the issue is with the optimization – Mehvish Ali Dec 09 '16 at 19:31
  • When exactly you get the OOM exception? – Haris Qureshi Dec 09 '16 at 19:51
  • @HarisQureshi I get particular exception when I move from 34 or 5 recyclerView items forward and backward to details activity and when I click on sixth one I fall prey to OOm. for the first few items it running smoothly – Mehvish Ali Dec 09 '16 at 19:53
  • And why you are adding views in your `instantiateItem`? Had you consider adding a fragment instead of using adding views in `container` – Haris Qureshi Dec 09 '16 at 19:54
  • actually I have no idea how many fragments will be required for that I've seen some implementations using fragments but they were defining the number of fragments. even I am not sure how many views will be required to instantiate as there may be variable number of images. – Mehvish Ali Dec 09 '16 at 19:58
  • Have look at [infinite viewpager](http://stackoverflow.com/questions/7766630/changing-viewpager-to-enable-infinite-page-scrolling), Its recommended to go with this approach. – Haris Qureshi Dec 09 '16 at 20:02
  • ok I am considering it – Mehvish Ali Dec 09 '16 at 20:08

0 Answers0