使用滑动库android分配65536016字节的内存不足

时间:2016-07-04 11:42:00

标签: java android memory memory-management android-glide

我已经尝试了很多东西来处理这个错误。当我在滑翔前使用毕加索时,我遇到了同样的问题。当我点击"更改照片"并从图库或相机等中选择一张照片,并希望在"更新活动"中设置所选图像。在图像视图中。它会抛出内存异常。我正在将图像大小调整为500x500并压缩它然后尝试在图像视图中设置它但它仍然没有内存。我想问题是我没有释放这个分配的内存但我搜索但是没有任何想法。提前致谢。



package com.donateblood.blooddonation;

/**
 * Created by YouCaf Iqbal on 6/29/2016.
 */
public class UpdateActivity  extends AppCompatActivity {
    @InjectView(R.id.image)
    ImageView _USERImage;
    @InjectView(R.id.input_name)
    EditText _nameText;
    @InjectView(R.id.btnchangephoto)
    Button changePhoto;
    @InjectView(R.id.input_password)
    EditText _passwordText;
    @InjectView(R.id.input_number)
    TextView _numText;
    public static boolean UpdatingPhoto = false;
    public String encodedPhotoString = null;
    public String ChangedName = null;
    public String ChangedPassword = null;
    public String ChangedContactNo = null;
    HashMap<String, String> ThingsTobeUpdated = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try{
            setContentView(R.layout.updateactivity);
            ButterKnife.inject(this);
        }catch (OutOfMemoryError e){
            Toast.makeText(getBaseContext(), "Sorry,Something went wrong, try again", Toast.LENGTH_SHORT).show();
        }

        ThingsTobeUpdated  = new HashMap<>();
        CheckImage();

        changePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdatingPhoto = true;
                Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
                startActivity(intent);
                UpdateActivity.this.finish();
            }
        });

    }

    public void CheckImage() {
        if (CroppingActivity.newImage != null) {

            Drawable drawable = _USERImage.getDrawable();
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            bitmap.recycle();
            CroppingActivity.newImage =  getResizedBitmap(CroppingActivity.newImage,500,500);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            CroppingActivity.newImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            Uri uri = getImageUri(CroppingActivity.newImage);
            String url = getRealPathFromURI(uri);
            File file = new File(url);
            Glide.with(UpdateActivity.this).load(file).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
                    .centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
           
            byte[] byte_arr = stream.toByteArray();
            encodedPhotoString = Base64.encodeToString(byte_arr, 0);

        } else {
            Glide.with(UpdateActivity.this).load(getImageURL()).override(400,400).placeholder(R.drawable.user).error(R.drawable.error)
                    .centerCrop().crossFade().bitmapTransform(new CropCircleTransformation(UpdateActivity.this)).into(_USERImage);
           
        }
    }
    // Resize the image ====================================
    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
    {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }

    public String getRealPathFromURI(Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = UpdateActivity.this.getContentResolver().query(contentUri,  proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public Uri getImageUri( Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(UpdateActivity.this.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getImageURL(){
        return "http://abdulbasit.website/blood_app/images/"+LoginActivity.ImageofLoggedINUser;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_update, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String ChangesHappened = "no";
        if (item.getItemId() == R.id.done_update) {
                // start updating process
            if(_nameText.getText().toString().equals("")){
                ChangedName = null;
            }else {
                ChangedName = _nameText.getText().toString();
                ChangesHappened = "yes";
            }
            if(_passwordText.getText().toString().equals("")){
                ChangedPassword = null;
            }else {
                ChangedPassword = _passwordText.getText().toString();
                ChangesHappened = "yes";
            }
            if(_numText.getText().toString().equals("")){
                ChangedContactNo = null;
            }else {
                ChangedContactNo = _numText.getText().toString();
                ChangesHappened = "yes";
            }
            if(encodedPhotoString!=null){
                ChangesHappened = "yes";
            }
            if(ChangesHappened=="yes"){
                 StartUpdate();
                 return true;
            }else {
                Toast.makeText(getBaseContext(), "Nothing to update", Toast.LENGTH_SHORT).show();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void StartUpdate() {
        ThingsTobeUpdated.put("email", LoginActivity.EmailofLoggedInUser);
        if (encodedPhotoString != null) {
            ThingsTobeUpdated.put("image", encodedPhotoString);
        }
        if (ChangedName != null) {
            ThingsTobeUpdated.put("name", ChangedName);
        }
        if (ChangedPassword != null) {
            ThingsTobeUpdated.put("password", ChangedPassword);
        }
        if (ChangedContactNo != null) {
            ThingsTobeUpdated.put("contact", ChangedContactNo);
        }
        UpdateAsync updatestart = new UpdateAsync();
        updatestart.execute();

    }


    public class UpdateAsync extends AsyncTask<Void, Void, Void> {

        private ProgressDialog pDialog;
        JSONObject json = null;
        @Override
        protected Void doInBackground(Void... voids) {
            json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/UpdateProfile.php", ThingsTobeUpdated);
            return null;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UpdateActivity.this);
            pDialog.setMessage("Updating profile...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();
            if (json != null) {
                Toast.makeText(getBaseContext(), "Profile updated, Login Again to see changes", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(getBaseContext(), "Error updating profile. Try Again", Toast.LENGTH_LONG).show();
            }
        }

    }
}
&#13;
public class CroppingActivity extends AppCompatActivity {

    private CropImageView mCropImageView;

    public static Bitmap finalImage = null;
    public static Bitmap newImage = null;
    private Uri mCropImageUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop);
        mCropImageView = (CropImageView) findViewById(R.id.CropImageView);

    }

    /**
     * On load image button click, start pick image chooser activity.
     */
    public void onLoadImageClick(View view) {
        startActivityForResult(getPickImageChooserIntent(), 400);
    }

    public void  onSetImageClick(View view) {

        if(UpdateActivity.UpdatingPhoto){
            newImage = mCropImageView.getCroppedImage(400, 400);
            try {
                Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
                startActivity(intent);
                finish();
            } catch (Exception e) {
                Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        }else {
            finalImage = mCropImageView.getCroppedImage(400, 400);
            try {
                Intent intent = new Intent(getApplicationContext(), UploadImage.class);
                startActivity(intent);
                finish();
            } catch (Exception e) {
                Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    }
    /**
     * Crop the image and set it back to the cropping view.
     */
    public void onCropImageClick(View view) {
        Bitmap cropped = mCropImageView.getCroppedImage(400, 400);
        if (cropped != null)
            mCropImageView.setImageBitmap(cropped);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = getPickImageResultUri(data);

            // For API >= 23 we need to check specifically that we have permissions to read external storage,
            // but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
            boolean requirePermissions = false;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                    checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                    isUriRequiresPermissions(imageUri)) {

                // request permissions and handle the result in onRequestPermissionsResult()
                requirePermissions = true;
                mCropImageUri = imageUri;
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
            if (!requirePermissions) {
                mCropImageView.setImageUriAsync(imageUri);
            }
        }
    }

    @Override
    public void onBackPressed() {
        UpdateActivity.UpdatingPhoto = false;
        super.onBackPressed();
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mCropImageView.setImageUriAsync(mCropImageUri);
        } else {
            Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * Create a chooser intent to select the source to get image from.<br/>
     * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
     * All possible sources are added to the intent chooser.
     */
    public Intent getPickImageChooserIntent() {

        // Determine Uri of camera image to save.
        Uri outputFileUri = getCaptureImageOutputUri();

        List<Intent> allIntents = new ArrayList<>();
        PackageManager packageManager = getPackageManager();

        // collect all camera intents
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            intent.setPackage(res.activityInfo.packageName);
            if (outputFileUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            }
            allIntents.add(intent);
        }

        // collect all gallery intents
        Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
        for (ResolveInfo res : listGallery) {
            Intent intent = new Intent(galleryIntent);
            intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            intent.setPackage(res.activityInfo.packageName);
            allIntents.add(intent);
        }

        // the main intent is the last in the list (android) so pickup the useless one
        Intent mainIntent = allIntents.get(allIntents.size() - 1);
        for (Intent intent : allIntents) {
            if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
                mainIntent = intent;
                break;
            }
        }
        allIntents.remove(mainIntent);

        // Create a chooser from the main intent
        Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");

        // Add all other intents
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));

        return chooserIntent;
    }

    /**
     * Get URI to image received from capture by camera.
     */
    private Uri getCaptureImageOutputUri() {
        Uri outputFileUri = null;
        File getImage = getExternalCacheDir();
        if (getImage != null) {
            outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
        }
        return outputFileUri;
    }

    /**
     * Get the URI of the selected image from {@link #getPickImageChooserIntent()}.<br/>
     * Will return the correct URI for camera and gallery image.
     *
     * @param data the returned data of the activity result
     */
    public Uri getPickImageResultUri(Intent data) {
        boolean isCamera = true;
        if (data != null && data.getData() != null) {
            String action = data.getAction();
            isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
        }
        return isCamera ? getCaptureImageOutputUri() : data.getData();
    }

    /**
     * Test if we can open the given Android URI to test if permission required error is thrown.<br>
     */
    public boolean isUriRequiresPermissions(Uri uri) {
        try {
            ContentResolver resolver = getContentResolver();
            InputStream stream = resolver.openInputStream(uri);
            stream.close();
            return false;
        } catch (FileNotFoundException e) {
            if (e.getCause() instanceof ErrnoException) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }
}
&#13;
 can't open /data/misc/app_oom.hprof: Permission denied
   07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap:  hprofDumpHeap failed with result: -1 
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm-heap: After hprofDumpHeap for process
   07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Out of memory: Heap Size=76760KB, Allocated=13818KB, Limit=98304KB, Proc Limit=98304KB
07-04 16:25:41.416 23278-23278/com.donateblood.blooddonation E/dalvikvm: Extra info: Footprint=76760KB, Allowed Footprint=76760KB, Trimmed=16KB
07-04 16:25:41.436 23278-23278/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.donateblood.blooddonation, PID: 23278
                                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.donateblood.blooddonation/com.donateblood.blooddonation.UpdateActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)  at android.app.ActivityThread.access$800(ActivityThread.java:156)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:157)
 at android.app.ActivityThread.main(ActivityThread.java:5872)
 at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
   at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
 at com.donateblood.blooddonation.UpdateActivity.CheckImage(UpdateActivity.java:93)
                                                                                   at com.donateblood.blooddonation.UpdateActivity.onCreate(UpdateActivity.java:76)
                                                                                   at android.app.Activity.performCreate(Activity.java:5312)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
&#13;
&#13;
&#13;

0 个答案:

没有答案