简体   繁体   中英

issue with onActivityResult in Android

Hi I have created an Activity from that I am calling startActivityForResult at the first time it is working below is the code

Dialog box for choosing image from Camera or Gallery

private void selectImage() {

    System.out.println("Select Image");

    final CharSequence[] items = { "Take Photo",
            "Choose from Library", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                final Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            } else if (items[item]
                    .equals("Choose from Library")) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(
                        intent, ""), PICK_IMAGE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

It's onActivityForResultSetMethod

     @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    System.out.println("onActivityResult");
    System.out.println("requestCode : - " + requestCode);
    System.out.println("resultCode : - " + resultCode);
    System.out.println("data : - " + data);

    if (resultCode != Activity.RESULT_CANCELED) {
        if (requestCode == PICK_IMAGE) {
            imagePath = getAbsolutePath(data.getData());
            bitmap = decodeFile(imagePath);
            ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
            ivUpload.setImageBitmap(bitmap);
        } else if (requestCode == CAPTURE_IMAGE) {
            imagePath = getImagePath();
            bitmap = decodeFile(imagePath);
            ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
            ivUpload.setImageBitmap(bitmap);
        } else {
            super.onActivityResult(requestCode, resultCode,
                    data);
        }
    }

}

Issue if when i first time called, In image view i am not getting image, and also if i tried it again

Activity's onCreate method is also called don't know but why

Try this way,hope this will help you to solve your problem.

    private int PICK_IMAGE=1;
    private int CAPTURE_IMAGE=2;
    private String imgPath;


    private void selectImage() {

        System.out.println("Select Image");

        final CharSequence[] items = { "Take Photo",
                "Choose from Library", "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                    startActivityForResult(intent, CAPTURE_IMAGE);
                } else if (items[item]
                        .equals("Choose from Library")) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PICK_IMAGE) {
                ivUpload.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
                ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
            } else if (requestCode == CAPTURE_IMAGE) {
                ivUpload.setImageBitmap(decodeFile(getImagePath()));
                ivUpload.setScaleType(ImageView.ScaleType.FIT_XY);
            }
        }

    }

    public Uri setImageUri() {
        // Store image in dcim
        File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
        Uri imgUri = Uri.fromFile(file);
        this.imgPath = file.getAbsolutePath();
        return imgUri;
    }

    public String getImagePath() {
        return imgPath;
    }
    public String getAbsolutePath(Uri uri) {
        if(Build.VERSION.SDK_INT >= 19){
            String id = uri.getLastPathSegment().split(":")[1];
            final String[] imageColumns = {MediaStore.Images.Media.DATA };
            final String imageOrderBy = null;
            Uri tempUri = getUri();
            Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                    MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
            if (imageCursor.moveToFirst()) {
                return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }else{
                return null;
            }
        }else{
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

    }

    private Uri getUri() {
        String state = Environment.getExternalStorageState();
        if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
            return MediaStore.Images.Media.INTERNAL_CONTENT_URI;

        return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    }

    public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

Note : please not forget this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Try This : I have done some modification.It is working on my end

public class MainActivity extends Activity {

    ImageView viewImage;
    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.btnSelectPhoto);
        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.main, menu);
        return true;
    }

    private void selectImage() {

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

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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(), "temp1.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
                            + "AudioBlog" + 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 from gallery......******************.........",
                        picturePath + "");
                viewImage.setImageBitmap(thumbnail);
            }
        }
    }
}

try this

private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;

private void selectImage() {

AlertDialog.Builder builder = new AlertDialog.Builder(
                ProfileActivity.this);
        // builder.setTitle("Choose Image Source");
        builder.setItems(new CharSequence[] { "Take a Photo",
                "Choose from Gallery" },
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                            Intent intent1 = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            intent1.putExtra(MediaStore.EXTRA_OUTPUT,
                                    setImageUri());
                            startActivityForResult(intent1, CAPTURE_IMAGE);
                            break;
                        case 1:
                            // GET IMAGE FROM THE GALLERY
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(
                                    Intent.createChooser(intent, ""),
                                    PICK_IMAGE);
                            break;
                        default:
                            break;
                        }
                    }
                });
        builder.show();
 }


  public Uri setImageUri() {

    File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
    Uri imgUri = Uri.fromFile(file);
    this.imgPath = file.getAbsolutePath();
    return imgUri;
}


public String getImagePath() {
    return imgPath;
}

onActivityForResultSetMethod

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_CANCELED) {
        if (requestCode == PICK_IMAGE) {
            selectedImagePath = getAbsolutePath(data.getData());
            System.out.println("path" + selectedImagePath);
            imageView.setImageBitmap(decodeFile(selectedImagePath));

        } else if (requestCode == CAPTURE_IMAGE) {
            selectedImagePath = getImagePath();
            System.out.println("path" + selectedImagePath);
            imageView.setImageBitmap(decodeFile(selectedImagePath));


        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}


 public Bitmap decodeFile(String path) {
    try {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, o);
        // The new size we want to scale to
        final int REQUIRED_SIZE = 70;

        // Find the correct scale value. It should be the power of
        // 2.
        int scale = 1;
        while (o.outWidth / scale / 2 >= REQUIRED_SIZE
                && o.outHeight / scale / 2 >= REQUIRED_SIZE)
            scale *= 2;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeFile(path, o2);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}


public String getAbsolutePath(Uri uri) {
    String[] projection = { MediaColumns.DATA };

    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

As to called onCreate() , please Log.d("~~~",""+savedInstanceState); , it will likely be non-null meaning that Android advices you to restore the application state from the bundle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM