不调用onActivityResult()。我无法显示图片

时间:2014-11-17 05:06:54

标签: android onactivityresult

我使用Intent来调用相机和图库。 我调用相机或图库,但不调用onActivityResult()。 我可以拍照并可以打开画廊,但我无法显示图片。 我应该在哪里修理? 请教我。

    public static class SelectImageDialog extends DialogFragment{
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState){
            AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
            builder.setMessage("please select").setPositiveButton("camera",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent=new Intent();
                    intent.setAction("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(intent,CAMERA);
                }
            }).setNegativeButton("gallery",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent=new Intent();
                    intent.setAction(intent.ACTION_GET_CONTENT);
                    intent.setType("image/*");
                    startActivityForResult(intent,GALLERY);
                }
            });
            return builder.create();
        }
    }

    @Override
    public void onActivityResult(int requestCode,int resultCode,Intent data){
        if(requestCode==CATEGORY){
            if(resultCode==RESULT_OK) {
                Bundle bundle = data.getExtras();
                textCategory.setText(bundle.getString("item"));
            }
        }else if(requestCode==GALLERY){
            if(resultCode==RESULT_OK){
                try{
                    InputStream is=getContentResolver().openInputStream(data.getData());
                    Bitmap bitmap=BitmapFactory.decodeStream(is);
                    imageButton.setImageBitmap(bitmap);
                    is.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if(requestCode==CAMERA){
            if(resultCode==RESULT_OK){
                Bitmap bitmap=(Bitmap)data.getExtras().get("data");
                imageButton.setImageBitmap(savePic(bitmap));
            }
        }
    }

    public Bitmap savePic(Bitmap bitmap){
        String path= Environment.getExternalStorageDirectory().getPath();
        String fileName = System.currentTimeMillis() + ".png";
        try {
            FileOutputStream outputStream = new FileOutputStream(path+"/"+fileName);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        String[] paths = {Environment.getExternalStorageDirectory().getPath()+"/"+fileName};
        String[] mimeType = {"image/png"};
        MediaScannerConnection.scanFile(getApplicationContext(), paths, mimeType, new MediaScannerConnection.OnScanCompletedListener() {
            @Override
            public void onScanCompleted(String s, Uri uri) {
            }
        });
        return bitmap;
    }

3 个答案:

答案 0 :(得分:0)

这就是我打电话的方式

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempFile = File.createTempFile("my_app", ".jpg");
fileName = tempFile.getAbsolutePath(); 
Uri uri = Uri.fromFile(fileName );
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri );
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent,CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);

答案 1 :(得分:0)

Intent intent = new Intent(
                                    Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");

                            Intent chooser = Intent
                                    .createChooser(
                                            intent,
                                            "Choose a Picture");
                            startActivityForResult(
                                    chooser,
                                    ACTION_REQUEST_GALLERY);

答案 2 :(得分:-2)

您可以从中找到解决方案:

final CharSequence[] options = { "Take Photo", "Choose from Gallery",
            "Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Select Profile Photo from");
    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;
                if (Build.VERSION.SDK_INT > 19) {
                    intent = new Intent(
                            Intent.ACTION_GET_CONTENT,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                } else {
                    intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                }

                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 0);
                intent.putExtra("aspectY", 0);
                intent.setType("image/*");
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 150);
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "gallery.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                intent.putExtra("return-data", true);
                startActivityForResult(intent, 2);
            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }

    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                previewCapturedImage("temp.jpg");

            } else if (requestCode == 2) {

                if (Build.VERSION.SDK_INT > 19) {
                    Uri selectedImage = data.getData();

                    setImageBitmapfromPath(getPath(selectedImage));

                } else {
                    previewCapturedImage("gallery.jpg");

                }

            }

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

@SuppressLint("NewApi")
private String getPath(Uri uri) {
    if (uri == null) {
        return null;
    }

    String[] projection = { MediaStore.Images.Media.DATA };

    Cursor cursor;
    if (Build.VERSION.SDK_INT > 19) {

        String wholeID = DocumentsContract.getDocumentId(uri);

        String id = wholeID.split(":")[1];

        String sel = MediaStore.Images.Media._ID + "=?";

        cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
                sel, new String[] { id }, null);
    } else {
        cursor = getActivity().getContentResolver().query(uri, projection,
                null, null, null);
    }
    String path = null;
    try {
        int column_index = cursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        path = cursor.getString(column_index).toString();
        cursor.close();
    } catch (NullPointerException e) {

    }
    return path;
}

@SuppressWarnings("deprecation")
private void setImageBitmapfromPath(String picturePath) {
    try {
        if (picturePath != null) {
            bitmap = decodeFile(new File(picturePath));
            Bitmap localBitmap1 = new RoundedTransformation(8, 0)
                    .transform(bitmap);
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap1.compress(Bitmap.CompressFormat.PNG, 10,
                    localByteArrayOutputStream);
            Bitmap localBitmap2 = BitmapFactory
                    .decodeStream(new ByteArrayInputStream(
                            localByteArrayOutputStream.toByteArray()));
            BitmapDrawable localBitmapDrawable = new BitmapDrawable(
                    getResources(), localBitmap2);

            iv_user_photo.setBackgroundDrawable(localBitmapDrawable);
            strImagepath = picturePath;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}




private void previewCapturedImage(String fName) {
    File f = new File(Environment.getExternalStorageDirectory().toString());
    for (File temp : f.listFiles()) {
        if (temp.getName().equals(fName)) {
            f = temp;
            break;
        }
    }
    setImageBitmapfromPath(f.getAbsolutePath());
}`