Sandeep R
Sandeep R

Reputation: 2292

onbackpressed for gallery intent ,Android

In my app , I select an image from gallery using startactivity for result. my code as follows

GALLERY.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

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

        }
    });

it all works fine, but the problem is ,when in gallery if i press back button , my app closes and returns me to home screen. For a normal activity there is a method called OnbackPressed to handle back button.But How do i achieve this in Gallery activity.

Upvotes: 3

Views: 1705

Answers (4)

latifalbr
latifalbr

Reputation: 173

Please handle result code first before handle request code

if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_FROM_CAMERA) {
    //your code
} 

Upvotes: 0

mike-gallego
mike-gallego

Reputation: 724

Surrounding the intent into a try and catch helped me. If there's an exception, like pressing the back button, I intent back to the activity i was at previously.

Upvotes: 0

user1650415
user1650415

Reputation:

You need to use ACTION_PICK intent :

    Intent intentImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);startActivityForResult(intentImage, RESULT_LOAD_IMAGE);


    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
    case RESULT_LOAD_IMAGE:
        if (resultCode == RESULT_OK && null != data) {
               Uri selectedImage = data.getData();
               String[] filePathColumn = { MediaStore.Images.Media.DATA };
               Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
               cursor.moveToFirst();
               int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
               Path = cursor.getString(columnIndex);
               setImage(Path);
               Toast.makeText(this, "File Clicked: "+picturePath, Toast.LENGTH_SHORT).show();
               cursor.close();
           }  
        break;

Upvotes: 0

Amit Gupta
Amit Gupta

Reputation: 8939

There are two ways to handle BackButton

1)

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Do Some thing Here
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

2)

    @Override
    public void onBackPressed() {
        // Do Some thing Here
        super.onBackPressed();

}

Upvotes: 1

Related Questions