Reputation: 45
I got this stupid memory problem when I am sending encoded Bitmap to another class:
java.lang.OutOfMemoryError: Failed to allocate a 5280012 byte allocation with 3645732 free bytes and 3MB until OOM
(It worked before but I don't know what is wrong with it now)
Here is my sender class:
public void ProfilePic(View view) {
Intent i = new Intent(Intent.ACTION_PICK , MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i , SELECTED_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case SELECTED_IMAGE:
if (resultCode==RESULT_OK){
Uri uri=data.getData();
String[]projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri , projection , null , null , null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath=cursor.getString(columnIndex);
cursor.close();
yourImage = BitmapFactory.decodeFile(filePath);
ProfilePic = new BitmapDrawable(yourImage);
imageView.setImageDrawable(ProfilePic);
}
break;
}
}
public static String encodeTobase64(Bitmap yourImage) {
Bitmap immage = yourImage;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
public void next2(View view) {
if(yourImage != null) {
SharedPreferences prefs = this.getSharedPreferences(
"PP", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("PP", encodeTobase64(yourImage));
edit.commit();
}
else {
SharedPreferences prefs = this.getSharedPreferences(
"PP", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("PP", "0");
edit.commit();
}
SharedPreferences p = this.getSharedPreferences(
"home_button", Context.MODE_PRIVATE);
SharedPreferences.Editor e = p.edit();
e.putBoolean("fr", true);
e.commit();
Intent i = new Intent(this , Results.class);
startActivity(i);
}
App crashes when entering "Results"-activity.
But, when I close the app and come back again, it goes straight into the Results-activity and everything looks fine (the sented picture is successfully sented)...
What causes this problem?
Upvotes: 1
Views: 337
Reputation: 37404
BitmapFactory.Options
will help you to simply reduce the size of bitmap. You can decide the size manually or you can simply use inSampleSize
field set to required value. Follow the link to load large bitmap efficiently
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=4;
yourImage =BitmapFactory.decodeFile(filePath,options)
Upvotes: 2