使用 Picasso 解决 OutOfMemoryError

Using Picasso to solve OutOfMemoryError

我已经看到很多关于这个问题的答案,但到目前为止对我来说都没有用,我得到的最好的选择是使用 Picasso 来解决这个问题,我已经导入了 .jar,但是我的代码出现了错误被告知要使用,我在下面的代码行中得到关于 this(context) 的错误,说 (context) cannot be resolved to a variable

Picasso.with(context).load(myBitmap).into(imageView);

这是产生错误的代码行,我打算使用 Picasso 解决

File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);

下面是我的完整代码

public class WidgetActivity extends Activity {
GridView grid;
Matrix matrix = new Matrix();
 Bitmap rotateimage;
 ArrayList<HashMap<String, String>> maplist = new  ArrayList<HashMap<String,String>>();
LocalStorageHandler notedb;
ImageView iv_notes;
EditText content;
LinearLayout grid_layout;
AppWidgetManager appWidgetManager;
int n;
Intent i;
int s;
String[] tcolor;
public String path = "", name = "", color = "";

public void onCreate(Bundle os) {
super.onCreate(os);
requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.dialog_shownotes);
notedb = new LocalStorageHandler(WidgetActivity.this);

grid = (GridView) findViewById(R.id.grid);
iv_notes = (ImageView) findViewById(R.id.iv_note);
content = (EditText) findViewById(R.id.content);
grid_layout = (LinearLayout) findViewById(R.id.grid_layout);
i = getIntent();
n = i.getIntExtra("currentWidgetId", 1);
new getlist().execute();

 }

 class getlist extends AsyncTask<String, String, String> {
 ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();

 @Override
 public void onPreExecute() {
    super.onPreExecute();

 }

 @Override
 protected String doInBackground(String... arg) {
    ArrayList<String> filepaths = new ArrayList<String>();
    ArrayList<String> filenames = new ArrayList<String>();
    Cursor dbCursor = notedb.get();
    if (dbCursor.getCount() > 0) {

        int noOfScorer = 0;
        dbCursor.moveToFirst();
        while ((!dbCursor.isAfterLast())
                && noOfScorer < dbCursor.getCount()) {
            noOfScorer++;
            try {
            HashMap<String, String> items = new HashMap<String, String>();

                filepaths.add(Environment.getExternalStorageDirectory()
                        + "/360notes/" + dbCursor.getString(2));
                filenames.add(dbCursor.getString(3));
                items.put("path",
                        Environment.getExternalStorageDirectory()
                                + "/360notes/" + dbCursor.getString(2));
                items.put("name", dbCursor.getString(3));
                items.put("time", dbCursor.getString(1));
                items.put("id", dbCursor.getString(0));
                items.put("color", dbCursor.getString(4));
                maplist.add(items);
            } catch (Exception e) {
                e.printStackTrace();
            }
            dbCursor.moveToNext();
        }
    }
    return null;
 }

 @Override
 protected void onPostExecute(String unused) {
    if (maplist.size() > 0) {
        grid.setAdapter(new GridViewImageAdapter(WidgetActivity.this,
                maplist));
    }

 }
}

public class GridViewImageAdapter extends BaseAdapter {

private Activity _activity;
ArrayList<String> _filenames = new ArrayList<String>();
private ArrayList<HashMap<String, String>> data = new   ArrayList<HashMap<String, String>>();

public GridViewImageAdapter(Activity activity,
        ArrayList<HashMap<String, String>> items) {
    this._activity = activity;
    data = items;

}

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

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

 @Override
 public long getItemId(int position) {

    return position;
 }

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

    LayoutInflater inflate = (LayoutInflater) _activity
            .getSystemService(_activity.LAYOUT_INFLATER_SERVICE);
    convertView = inflate.inflate(R.layout.show_image, null);
    ImageView imageView = (ImageView) convertView
            .findViewById(R.id.imgScreen);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    try {
        String[] tcolor = data.get(position).get("name").split(" / ");
        title.setText(tcolor[0].trim());
        title.setTextColor(Color.parseColor(tcolor[1].trim()));

        if (tcolor[2].trim().equals("0")) {
            String text = title.getText().toString();
            SpannableString span = new SpannableString(text);
            span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
            // title.setText(span);
        } else if (tcolor[2].trim().equals("3")) {
            // title.setTypeface(null, Typeface.BOLD);

            String text = title.getText().toString();
            SpannableString span = new SpannableString(text);
            span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
            // title.setText(span);

        } else if (tcolor[2].trim().equals("4")) {
            // title.setTypeface(null, Typeface.ITALIC);

            String text = title.getText().toString();
            SpannableString span = new SpannableString(text);
            span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
            // title.setText(span);
        } else if (tcolor[2].trim().equals("1")) {
            // title.setTypeface(null, Typeface.BOLD);
            String text = title.getText().toString();

            SpannableString span = new SpannableString(text);

            span.removeSpan(text);
        } else if (tcolor[2].trim().equals("2")) {
            // title.setTypeface(null, Typeface.ITALIC);
            String text = title.getText().toString();

            SpannableString span = new SpannableString(text);

            span.removeSpan(text);
        } else {
            String text = title.getText().toString();

            SpannableString span = new SpannableString(text);

            span.removeSpan(text);
        }

    } catch (IndexOutOfBoundsException e) {
        // TODO: handle exception
    }
    // TODO: handle exception
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;

    File imgFile = new File(data.get(position).get("path"));
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    imageView.setImageBitmap(myBitmap);

    /*if (myBitmap != null && !myBitmap.isRecycled()) {
        myBitmap.recycle();
        myBitmap = null;
    }*/
     //myBitmap.recycle();
     //myBitmap = null;
    Picasso.with(context).load(myBitmap).into(imageView);

    grid.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            grid.setVisibility(View.GONE);

            // grid_layout.setVisibility(View.VISIBLE);
            s = position;
            path = data.get(position).get("path");
            try {

                tcolor = data.get(position).get("name").split(" / ");
                name = tcolor[0].trim();
                color = tcolor[1].trim();

            } catch (IndexOutOfBoundsException e) {
                name = "";
                color = "#000000";
            }
            appWidgetManager = AppWidgetManager
                    .getInstance(WidgetActivity.this);
            UnreadWidgetProvider.updateWidget(WidgetActivity.this,
                    appWidgetManager, n, path,
                    data.get(position).get("name"), color, s);
            finish();
        }
    });
    return convertView;
  }
}

public void images(String path, String name, String color) {
 try {
    Bitmap bm;
    try {
        bm = decodeSampledBitmapFromResource(path);
        ExifInterface exifReader = new ExifInterface(path);
        int orientation = exifReader.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, -1);

        if (orientation == ExifInterface.ORIENTATION_NORMAL) {

            matrix.postRotate(360);
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {

            // matrix.postRotate(90);
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {

            // matrix.postRotate(180);
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            // matrix.postRotate(270);
        } else if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
            // matrix.postRotate(90);
        } else {
        }
        rotateimage = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                bm.getHeight(), matrix, true);
        iv_notes.setImageBitmap(rotateimage);
        content.setText(name);
        content.setFocusable(false);
        try {
            String[] tcolor = name.split(" / ");
            content.setText(tcolor[0].trim());
            content.setTextColor(Color.parseColor(tcolor[1].trim()));

            if (tcolor[2].trim().equals("0")) {
                String text = content.getText().toString();
                SpannableString span = new SpannableString(text);
                span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
                // content.setText(span);
            } else if (tcolor[2].trim().equals("3")) {
                // content.setTypeface(null, Typeface.BOLD);

                String text = content.getText().toString();
                SpannableString span = new SpannableString(text);
                span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
                // content.setText(span);

            } else if (tcolor[2].trim().equals("4")) {
                // content.setTypeface(null, Typeface.ITALIC);

                String text = content.getText().toString();
                SpannableString span = new SpannableString(text);
                span.setSpan(new UnderlineSpan(), 0, span.length(), 0);
                // content.setText(span);
            } else if (tcolor[2].trim().equals("1")) {
                // content.setTypeface(null, Typeface.BOLD);
                String text = content.getText().toString();

                SpannableString span = new SpannableString(text);

                span.removeSpan(text);
            } else if (tcolor[2].trim().equals("2")) {
                // content.setTypeface(null, Typeface.ITALIC);
                String text = content.getText().toString();

                SpannableString span = new SpannableString(text);

                span.removeSpan(text);
            } else {
                String text = content.getText().toString();

                SpannableString span = new SpannableString(text);

                span.removeSpan(text);
            }

        } catch (IndexOutOfBoundsException e) {
            // TODO: handle exception
        }
        grid_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                int i = grid.getCount();
                Intent intentAlarm = new Intent(WidgetActivity.this,
                        WriteNotesActivity.class);
                intentAlarm.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intentAlarm.putExtra("max", s);
                startActivity(intentAlarm);
                finish();

            }
        });
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
 } catch (Exception e) {
    // finish();
  }
 }

public static Bitmap decodeSampledBitmapFromResource(String resId) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 400, 300);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, options);
 }

public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {

    final int halfHeight = height / 2;
    final int halfWidth = width / 2;

    // Calculate the largest inSampleSize value that is a power of 2 and
    // keeps both
    // height and width larger than the requested height and width.
    while ((halfHeight / inSampleSize) > reqHeight
            || (halfWidth / inSampleSize) > reqWidth) {
        inSampleSize *= 2;
    }
}

 return inSampleSize;
}
}

这可能会对几个小时后仍未得到解答的人有所帮助。我找到了一种不使用 Picasso 来处理 outOfMemoryError 的方法来解决这个问题。我在我的清单文件中添加了这行代码。

android:largeHeap="true"

我将其添加到整个应用程序中,如下所示:-

<application
    android:icon="@drawable/ic_launcher"
    android:largeHeap="true"
    android:label="@string/app_name" >

android:largeHeap 是增加分配给应用程序的内存的工具。

编辑: 好吧,你使用了太多的内存。删除那 3 行代码:

File imgFile = new File(data.get(position).get("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);

简单地说,您为这些实例分配了过多的 space 并且您的 phone 内存不足。只需使用我的回复并考虑记录文件路径,这样您就可以在不创建另一个文件的情况下使用它。

我认为您使用了错误的实现方式。可能上下文地址不正确,因此,我个人会使用 "this" 代替。而对于加载资源,他们的指南为我们提供了三种实现方式,见下:

传递可绘制对象

Picasso.with(context).load(R.drawable.landing_screen).into(imageView1);

传递 uri

Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);

传递文件

Picasso.with(context).load(new File(...)).into(imageView3);

因此我将使用以下代码解码图像:

Picasso.with(this).load(new File(data.get(position).get("path"))).into(imageView);