使用Galaxy S4打开onActivityResult时,应用程序崩溃

时间:2016-01-16 18:05:38

标签: android camera

我有一个活动拍摄照片,然后使用捕获的图像设置图像视图,然后将其上传到解析。 它与LG G4完美搭配,但是在我按下按钮说明我想要这张照片后,它会崩溃,它会在OnActivityResult功能中崩溃。 我在日志中看到有一个nullpointerexception,我想因为galaxy s4比LG G4有更少的内存。 我想我理解这个问题(我对记忆的假设),但不知道如何解决它。

活动

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SituationStatusActivity extends AppCompatActivity {

    ImageView imVCature_pic_nir;
    ImageView imVCature_pic_sharon;

    private static final int REQUEST_CODE = 1;

    String imageFilePath;
    public SharedPreferences startExplePref;
    public String user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_situation_status);
        if(savedInstanceState!=null){
            imageFilePath = savedInstanceState.getString("path");
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        overridePendingTransition(R.anim.fadein, R.anim.fadeout);

//       get the user
        startExplePref = PreferenceManager.getDefaultSharedPreferences(this);
        user = startExplePref.getString("user", "");
//        upload nir Pic

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFilePath = Environment.getExternalStorageDirectory().toString() + "/Android/data/com.my.app/Image-" + timeStamp + ".png";

        imVCature_pic_nir = (ImageView) findViewById(R.id.nirPic);
        imVCature_pic_sharon = (ImageView) findViewById(R.id.sharonPic);

        Button uploadPic = (Button) findViewById(R.id.picUploadButton);
        uploadPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    /*************************** Camera Intent Start ************************/
                File imageFile = new File(imageFilePath);
                Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
                // Standard Intent action that can be sent to have the camera
                // application capture an image and return it.
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);   // set the image file name
                startActivityForResult(intent, 1);
                /*************************** Camera Intent End ************************/
            }
        });

        UpdatePic();

    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putString("path", imageFilePath);

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
// if picture was taken
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            bmpFactoryOptions.inSampleSize = 5;
            bmpFactoryOptions.inJustDecodeBounds = false;

            //imageFilePath image path which you pass with intent
            Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

            //rotate image by 90 degrees
            Matrix rotateMatrix = new Matrix();
            rotateMatrix.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
//
            Drawable d = new BitmapDrawable(rotatedBitmap);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
//            // Compress image to lower quality scale 1 - 100
            rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] image = stream.toByteArray();
//
//            // Create the ParseFile
            ParseFile file = new ParseFile("image.png", image);
//            // Upload the image into Parse Cloud
            file.saveInBackground();
//
//            // Create a New Class called "ImageUpload" in Parse
            ParseObject SituationPic = new ParseObject("SituationPic");
//
//            // Create a column named "ImageName" and set the string
            SituationPic.put("ImageName", "First Pic");
//
            SituationPic.put("user", user);

//            // Create a column named "ImageFile" and insert the image
            SituationPic.put("ImageFile", file);
//
//            // Create the class and the columns
            SituationPic.saveInBackground();

            if (user.equals("nir")) {
                imVCature_pic_nir.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap, 500));
                imVCature_pic_nir.setScaleType(ImageView.ScaleType.FIT_XY);

            } else if (user.equals("sharon")) {
                imVCature_pic_sharon.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap, 500));
                imVCature_pic_sharon.setScaleType(ImageView.ScaleType.FIT_XY);

            } else {
                Toast.makeText(SituationStatusActivity.this, "error", Toast.LENGTH_LONG).show();
            }

//       if picture was not taken
        } else {
            Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_LONG).show();
        }
//        UpdatePic();
    }


    public Bitmap nirBitmap;
    public Bitmap sharonBitmap;
    //change it to load in the beginiing
    public void UpdatePic()
    {
//        Update photo of nir
        ParseQuery<ParseObject> querynir = ParseQuery.getQuery("SituationPic");
        querynir.orderByDescending("updatedAt");
        querynir.whereEqualTo("user", "nir");
        querynir.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                ParseObject object = objects.get(0);
                ParseFile applicantResume = (ParseFile) object.get("ImageFile");
                applicantResume.getDataInBackground(new GetDataCallback() {
                    public void done(byte[] data, ParseException e) {
                        if (e == null) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
                                    data.length);
                            Matrix rotateMatrix = new Matrix();
                            rotateMatrix.postRotate(360);
                            Bitmap rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), rotateMatrix, false);
                            nirBitmap = rotatedBitmap;
                            imVCature_pic_nir.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap, 500));
                            imVCature_pic_nir.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                    }
                });
            }
        });

        //        Update photo of sharon
        ParseQuery<ParseObject> querySHN = ParseQuery.getQuery("SituationPic");
        querySHN.orderByDescending("updatedAt");
        querySHN.whereEqualTo("user", "sharon");
        querySHN.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                ParseObject object = objects.get(0);

                ParseFile applicantResume = (ParseFile) object.get("ImageFile");
                applicantResume.getDataInBackground(new GetDataCallback() {
                    public void done(byte[] data, ParseException e) {
                        if (e == null) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
                                    data.length);
                            Matrix rotateMatrix = new Matrix();
                            rotateMatrix.postRotate(180);
                            Bitmap rotatedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), rotateMatrix, false);

                            sharonBitmap = rotatedBitmap;


                            imVCature_pic_sharon.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap, 500));
                            imVCature_pic_sharon.setScaleType(ImageView.ScaleType.FIT_XY);
                        }
                    }
                });
            }
        });

    }

    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }


}

LogCat

FATAL EXCEPTION: main
                                                                               Process: fastner.israel.nir_zabari.onelove, PID: 31324
                                                                               java.lang.RuntimeException: Unable to resume activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3394)
                                                                                   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3425)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2763)
                                                                                   at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4462)
                                                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:177)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1454)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                   at android.os.Looper.loop(Looper.java:145)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5942)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
                                                                                Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:4058)                                                                                    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3380)
                                                                                   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3425) 
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2763) 
                                                                                   at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4462) 
                                                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:177) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1454) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:145) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5942) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195) 
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                   at fastner.israel.nir_zabari.onelove.SituationStatusActivity.onActivityResult(SituationStatusActivity.java:117)
                                                                                   at android.app.Activity.dispatchActivityResult(Activity.java:6549)
                                                                                   at android.app.ActivityThread.deliverResults(ActivityThread.java:4054)
                                                                                   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3380) 
                                                                                   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3425) 
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2763) 
                                                                                   at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4462) 
                                                                                   at android.app.ActivityThread.access$1000(ActivityThread.java:177) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1454) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                   at android.os.Looper.loop(Looper.java:145) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5942) 
                                                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195) 

1 个答案:

答案 0 :(得分:0)

在使用解码位图进行任何工作之前,您需要检查它是否实际上已经解码好了。

// Code above
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
    BitmapFactory.Options bmpFactoryOptions = new mapFactory.Options();
    bmpFactoryOptions.inJustDecodeBounds = true;
    bmpFactoryOptions.inSampleSize = 5;
    bmpFactoryOptions.inJustDecodeBounds = false;

    //imageFilePath image path which you pass with intent
    Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
    if (bp != null) {
        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(90);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
    }
// Code below