在拍摄照片并在Android Marshmallow中点击确定后相机崩溃了。?

时间:2015-10-27 14:44:06

标签: android android-camera android-6.0-marshmallow

我是Android新手。我在我的Android应用程序中创建了ImageUpload Activity,但它在Apk(23)下工作正常。但每当我在Android Marshmallow上尝试它时,它会在点击图片后崩溃。

这是我的最终文件

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<application
    android:name=".ParseApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Image"></activity>
    <activity android:name=".Main"></activity>
    <activity android:name=".SingleItemView"></activity>
</application>

这是主要活动

ImageView viewImage;
Button b;
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload);
    b=(Button)findViewById(R.id.btnSelectPhoto);
    bt=(Button)findViewById(R.id.uploadbtn);
    viewImage=(ImageView)findViewById(R.id.viewImage);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds options to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

private void selectImage() {

    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(Image.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);
            }
            else if (options[item].equals("Choose from Gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);

            }
            else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions);

                viewImage.setImageBitmap(bitmap);

                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {

            Uri selectedImage = data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image ", picturePath + "");
            viewImage.setImageBitmap(thumbnail);
        }
    }


    bt.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            bt.setOnClickListener(this);



            // Locate the image in res > drawable-hdpi
            //Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
            //      R.id.viewImage);
            Bitmap bitmap = ((BitmapDrawable)viewImage.getDrawable()).getBitmap();
            // Convert it to byte
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // Compress image to lower quality scale 1 - 100
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
            byte[] image = stream.toByteArray();

            // Create the ParseFile
            ParseFile file = new ParseFile("temp.jpg", image);
            // Upload the image into Parse Cloud
            file.saveInBackground();



            // Create a New Class called "ImageUpload" in Parse
            ParseObject imgupload = new ParseObject("ImageUpload");

            // Create a column named "ImageName" and set the string
            imgupload.put("ImageName", "Android");

            // Create a column named "ImageFile" and insert the image
            imgupload.put("ImageFile", file);

            // Create the class and the columns
            imgupload.saveInBackground();

            // Show a simple toast message
            Toast.makeText(Image.this, "Image Uploaded",
                    Toast.LENGTH_SHORT).show();
            Intent i = new Intent(getApplicationContext(), Main.class);
            startActivity(i);

        }
    });
}}

HERE IS LOG

  

java.lang.RuntimeException:将结果ResultInfo {who = null,request = 1,result = -1,data = Intent {}}传递给activity {com.example.user.mnc / com.example.user。 mnc.Image}:java.lang.NullPointerException:尝试获取null数组的长度               在android.app.ActivityThread.deliverResults(ActivityThread.java:3699)               在android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)               在android.app.ActivityThread.-wrap16(ActivityThread.java)               在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1393)               在android.os.Handler.dispatchMessage(Handler.java:102)               在android.os.Looper.loop(Looper.java:148)               在android.app.ActivityThread.main(ActivityThread.java:5417)               at java.lang.reflect.Method.invoke(Native Method)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)        引起:java.lang.NullPointerException:尝试获取null数组的长度               在com.example.user.mnc.Image.onActivityResult(Image.java:99)

2 个答案:

答案 0 :(得分:0)

您必须在Android M上询问运行时权限。

http://developer.android.com/intl/es/training/permissions/requesting.html

的更多信息

答案 1 :(得分:0)

您的活动文件

private Button takePictureButton;
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    takePictureButton = (Button) findViewById(R.id.button_image);
    imageView = (ImageView) findViewById(R.id.imageview);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        takePictureButton.setEnabled(false);
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 0) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            takePictureButton.setEnabled(true);
        }
    }
}

public void takePicture(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    file = Uri.fromFile(getOutputMediaFile());
    intent.putExtra(MediaStore.EXTRA_OUTPUT, file);

    startActivityForResult(intent, 100);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 100) {
        if (resultCode == RESULT_OK) {
            imageView.setImageURI(file);
        }
    }
}

private static File getOutputMediaFile(){
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "CameraDemo");

    if (!mediaStorageDir.exists()){
        if (!mediaStorageDir.mkdirs()){
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    return new File(mediaStorageDir.getPath() + File.separator +
                "IMG_"+ timeStamp + ".jpg");
}

如果您想使用非常通用的布局文件进行测试,可以使用:

<ImageView
    android:id="@+id/imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_above="@+id/button_image"/>

    <Button
        android:id="@+id/button_image"
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="takePicture"
        android:text="Take a picture!"/>

预设文件 另外,请记住更新权限:

<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />