OutOfMemoryError ViewPager活动

时间:2016-12-09 18:24:55

标签: android android-viewpager out-of-memory

其中一个活动包含RecyclerView,其中呈现某些项目,并且在点击任何项目时,它移动到另一个活动,该活动具有来自服务器的大量数据,它就像一个新闻的详细页面以及来自的图像服务器在其库部分中使用ViewPager PagerAdapter进行渲染(某些新闻文章可能包含20-30张图片。 每当我从这些活动中向前和向后移动时,我的应用程序都会与OutOfMemory Error崩溃。 到目前为止,我已经尝试在从详细活动返回到包含System.gc()但仍然出现OutOfMemory错误的活动之后调用finish()然后调用RecyclerView。 我知道它的内存泄漏是因为它获取了大量数据,然后在活动的不同位置呈现,但不知道如何处理它。 我已经阅读了一些提及android:largeHeap的解决方案,但它也没有保证你可能会因为频繁的抨击而得到大量的其他缺点。

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;


    }
}
来自列表活动的

和我的RecyclerAdapter

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();
    }

}

NewsAdapter.onCreateViewHolder的错误声明 OutOfMemory错误(NewsAdapter.java:49) 调用onCreateViewHolder的地方。

0 个答案:

没有答案