内存不足,无法使用可绘制图像

问题描述 投票:0回答:1

我正在创建一个用于交流学习的Android应用程序

我想在具有分页功能的活动中显示250张图像,但是当我从可绘制图像中获取图像时,它变成了错误OutOfMemoryError

也许我需要按系统调整图像大小,但我不知道该怎么做

当我尝试使用位图时,图像没有出现

在此代码中的适配器中发生

Drawable res = context.getResources().getDrawable(imageResource);

这是适配器

public class ContentAdapter extends BaseAdapter {

    private Context context;
    private List<Content> contents;

    public ContentAdapter(Context context, List<Content> contents) {
        this.context = context;
        this.contents = contents;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View gridView;

            gridView = convertView;

            // get layout from mobile.xml
            gridView = inflater.inflate(R.layout.adapter_content, null);

            // set value into textview
            TextView textView = (TextView) gridView
                    .findViewById(R.id.grid_item_label);
            textView.setText(contents.get(position).getTitle());

            // set image based on selected text
            ImageView imageView = (ImageView) gridView
                    .findViewById(R.id.grid_item_image);

            try {
                String uri = "@drawable/" + contents.get(position).getPathImage().split("\\.")[0];  
                Log.e("================", uri);
                int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
                Drawable res = context.getResources().getDrawable(imageResource); //error OOM in this line
                imageView.setImageDrawable(res);
            }
            catch(Exception ex) {

                File imgFile = new  File(context.getFilesDir().getAbsolutePath() + "/img_content"
                        + "/content_" + contents.get(position).getId() + ".jpg");

                if(imgFile.exists()){
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 8;
                    Bitmap myBitmap  = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
                    imageView.setImageBitmap(myBitmap);

                } else {
                    imageView.setImageResource(R.drawable.ic_menu_camera);
                }
            }

        return gridView;
    }

    @Override
    public int getCount() {
        return contents.size();
    }

    @Override
    public Object getItem(int position) {
        return contents.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}

这是Model

public class Content extends Base {

    private int level;
    private int themeId;
    private int categoryId;
    private String title;
    private String pathImage;
    private String pathSound;
    private String level1;

    public String getLevel1() {
        return level1;
    }

    public void setLevel1(String level1) {
        this.level1 = level1;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public int getThemeId() {
        return themeId;
    }

    public void setThemeId(int themeId) {
        this.themeId = themeId;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPathImage() {
        return pathImage;
    }

    public void setPathImage(String pathImage) {
        this.pathImage = pathImage;
    }

    public String getPathSound() {
        return pathSound;
    }

    public void setPathSound(String pathSound) {
        this.pathSound = pathSound;
    }

    @Override
    public String toString() {
        return "Content{" +
                "categoryId=" + categoryId +
                ", title='" + title + '\'' +
                ", pathImage='" + pathImage + '\'' +
                ", pathSound='" + pathSound + '\'' +
                '}';
    }
}

并且,这是活动

public class BoardContentDialog extends Dialog {

    private ListView lvFcmData;
    private ContentDao contentDao;
    private BoardInterface boardInterface;
    private Context context;

    private int categoryId;
    private int level;
    private int row;
    private int col;

    boolean isSemua = false;
    boolean isSearch = false;
    private String kategori;
    private String kontenYangDicari;

    List<Content> contents = null;
    List<Content> contentSearch;

    int halamanYangMuncul = 0;

    public BoardContentDialog(@NonNull Context context, BoardInterface boardInterface, int categoryId,
                              int level, int row, int col) {
        super(context);
        this.context = context;
        this.boardInterface = boardInterface;
        this.categoryId = categoryId;
        this.level = level;
        this.row = row;
        this.col = col;
    }
    public BoardContentDialog(@NonNull Context context, BoardInterface boardInterface, String kategori,
                              int level, int row, int col) {
        super(context);
        this.context = context;
        this.boardInterface = boardInterface;
        this.kategori = kategori;
        this.isSemua = true;
        this.level = level;
        this.row = row;
        this.col = col;
    }

    public BoardContentDialog(@NonNull Context context, BoardInterface boardInterface, String kontenYangDicari,
                              int level, int row, int col, boolean isSearch) {
        super(context);
        this.context = context;
        this.boardInterface = boardInterface;
        this.kontenYangDicari = kontenYangDicari;
        this.isSearch = isSearch;
        this.level = level;
        this.row = row;
        this.col = col;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.dialog_board_content);

        contentDao = new ContentDao(context);
        contentDao.open();

        Button next = findViewById(R.id.BtnContentPageNext);
        Button prev = findViewById(R.id.BtnContentPagePrev);


        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BoardContentDialog.this.dismiss();
            }
        });

        if(isSemua == true){
            contents = contentDao.getContentByCategory(kategori, level);

        }else if(isSearch == true){
            contents = contentDao.getContentBySearch(kontenYangDicari, level);

        } else {
            contents = contentDao.getContentByCategoryId(categoryId);
        }

        bindData(halamanYangMuncul);
        prev.setEnabled(false);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                halamanYangMuncul = halamanYangMuncul+1;
                bindData(halamanYangMuncul);
                toggleButtons();
            }
        });
        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                halamanYangMuncul = halamanYangMuncul-1;
                bindData(halamanYangMuncul);
                toggleButtons();
            }
        });

    }

    public int jumlahContent(){
        return contents.size();
    }

    public int jumlahHalaman(){
        int kontenTersisa = jumlahContent()%50;

        if(kontenTersisa > 0){
            return jumlahContent()/50;
        }
        return (jumlahContent()/50)-1;
    }

    public ArrayList<Content> contentsTersisa (int halamanSekarang){
        int contentAwal = halamanSekarang*50;
        int contentTerakhir = contentAwal+50;

        ArrayList<Content> contentSekarang = new ArrayList<>();

        try {
            for (int i=0; i<jumlahContent(); i++){
                if (i >= contentAwal && 1 < contentTerakhir){
                    contentSekarang.add(contents.get(i));
                }
            }
            return contentSekarang;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private void toggleButtons(){
        if (jumlahHalaman() <=1){
            //kalo halaman cman 1
            findViewById(R.id.BtnContentPageNext).setEnabled(false);
            findViewById(R.id.BtnContentPagePrev).setEnabled(false);
        } else if (halamanYangMuncul == jumlahHalaman()){
            //halaman terakhir
            findViewById(R.id.BtnContentPageNext).setEnabled(false);
            findViewById(R.id.BtnContentPagePrev).setEnabled(true);
        } else if (halamanYangMuncul == 0){
            //halaman awal
            findViewById(R.id.BtnContentPageNext).setEnabled(true);
            findViewById(R.id.BtnContentPagePrev).setEnabled(false);
        } else if (halamanYangMuncul >= 1 && halamanYangMuncul <= jumlahHalaman()){
            //sisanya
            findViewById(R.id.BtnContentPageNext).setEnabled(true);
            findViewById(R.id.BtnContentPagePrev).setEnabled(true);
        }


    }

    private void bindData (int halaman){

        GridView gvContent = findViewById(R.id.content_list_grid);



        gvContent.setAdapter(new ContentAdapter(context, contentsTersisa(halaman)));
        gvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                boardInterface.onBoardAdded(level, row, col, contents.get(position).getId());
                BoardContentDialog.this.dismiss();
                contentDao.close();
            }
        });

    }

}
java android out-of-memory
1个回答
0
投票

使用第三方库来加载图像并为您处理内存使用情况例如:Glide

替换

imageView.setImageDrawable(res)

使用

Glide.with(this).load(res).into(imageView);
© www.soinside.com 2019 - 2024. All rights reserved.