Home java Android, how to choose the right photo from the gallery

Android, how to choose the right photo from the gallery

Author

Date

Category

You need to choose a photo from the gallery. Here is the code in which when clicking in the gallery:

intent i = new intent (intent.action_pick);
i.settype ("image / *");
StartatoryIForResult (I, Constants.Request);

Here is the override of the OnactivityResult method:

Public void onactivityResult (Int Requestcode, Int ResultCode, Intent Data) {
  Bitmap img = null;
      If (RequestCode == Constants.Request) {
        URI SELECTEDIMAGE = DATA.GETDATA ();
        Try {
          img = mediastore.images.media.getBitmap (getContext (). GetContentResolver (), selectedImage);
        } Catch (IoException E) {
          E.PrintStackTrace ();
        }
        circleimageview.setimagebitmap (IMG);
      }
super.onactivityResult (RequestCode, ResultCode, Data);
  }

Everything starts, everything is fine, but when you select the photo it does not return to the app and does not put a photo in ImageView. Through logging, I learned that it was not running onactivityResult. What to do ?

Update

Everything happens in a fragment. I thought about this and mistake, but in the onactivityResult method in activity, nothing happens.


Answer 1, Authority 100%

If you call StartActivity From the fragment, then OnactivityResult you need to catch in a fragment, and if from Activity then in Activity

An example of a working code (used in the project):

intent intent = new intent ();
          INTENT.SETTYPE ("image / *");
          Intent.SetAction (Intent.action_pick);
          StartActivityForResult (Intent.createChooser (Intent, "Select Picture"), Pick_image_avatar);

Next onactivityResult:

if (RequestCode == Pick_image_avatar & amp; & amp; data! = null) {
        URI SELECTEDIMAGE = DATA.GETDATA ();
        // Create File.
        Cursor c = getContentResolver (). Query (SelectedImage, NULL, NULL, NULL, NULL);
        c.movetofirst ();
        STRING PATH = C.GetString (C.Getcolumnindex (MediaStore.mediaColumns.data));
        File File = New File (imagepickuputil.getRealPathFromuri (this, selectedImage));
        ...
}

At the request of ImagePickuputil:

Public Class ImagePickuputil {
    Public Static Final int pick_code = 100;
    / **
     * Detect The Available Intens and Open a New Dialog.
     *
     * @param context
     * /
    Public Static Void OpenMediaSelector (Activity Context) {
      INTENT CAMINTENT = NEW INTENT ("Android.media.action.image_capture");
      INTENT GALLINTENT = NEW INTENT (INTENT.ACTION_PICK);
      Gallintent.Settype ("image / *");
  // Look for Available Intens
      List & lt; ResolveInfo & gt; info = new arraylist & lt; resolveinfo & gt; ();
      List & LT; Intent & GT; YourintensList = New ArrayList & LT; INTENT & GT; ();
      Packagemanager packagemanager = context.getpackagemanager ();
      List & lt; ResolveInfo & gt; listcam = packagemanager.queryintentactivities (Camintent, 0);
      For (ResolveInfo Res: Listcam) {
        Final Intent Finalintent = New Intent (Camintent);
        Finalintent.Setcomponent (new componentname (res.ractivityinfo.packagename, res.activityInfo.name));
        YourintensList.Add (finalintent);
        info.add (RES);
      }
      List & lt; ResolveInfo & gt; ListGall = Packagemanager.QueryIntentAntivities (Gallintent, 0);
      For (ResolveInfo Res: ListGall) {
        Final Intent Finalintent = New Intent (Gallintent);
        Finalintent.Setcomponent (new componentname (res.ractivityinfo.packagename, res.activityInfo.name));
        YourintensList.Add (finalintent); 
info.add (RES);
      }
  // Show Available Intens
      Opendialog (Context, YourintensList, Info);
    }
    / **
     * Open a New Dialog with the Detected Items.
     *
     * @param context
     * @Param Intens
     * @Param ActivitiesInfo.
     * /
    Private Static Void Opendialog (Final Activity Context, Final List & LT; Intent & GT; Intens,
                    List & lt; ResolveInfo & gt; ActivitiesInfo) {
      Alertdialog.builder dialog = new alertdialog.builder (CONTEXT);
      Dialog.Settitle ("Select Action");
      Dialog.Setadapter (Buildadapter (Context, ActivitiesInfo),
          new dialoginterface.onclicklistener () {
            @Override
            Public Void OnClick (DialogInterface Dialog, Int ID) {
              INTENT INTENT = INTENTS.GET (ID);
              context.startactivityforResult (INTENT, PICK_CODE);
            }
          });
      Dialog.setNeutralButton ("Cancel",
          new android.content.dialoginterface.onclicklistener () {
            @Override
            Public Void OnClick (DialogInterface Dialog, Int Which) {
              dialog.dismiss ();
            }
          });
      dialog.show ();
    }
    / **
     * Build The List of Items To Show Using The Intent_ListView_ROW Layout.
     *
     * @param context
     * @Param ActivitiesInfo.
     * @return
     * /
    Private Static Arrayadapter & LT; ResolveInfo & GT; Buildadapter (Final Context Context, Final List & LT; ResolveInfo & GT; ActivitiesInfo) {
      Return New Arrayadapter & LT; ResolveInfo & GT; (Context, R.Layout.intent_ListView_ROW, R.ID.TITLE, ActivitiesInfo) {
        @Override
        Public View GetView (Int Position, View ConvertView, ViewGroup Parent) {
          View View = Super.GetView (Position, ConvertView, Parent);
          ResolveInfo Res = ActivitiesInfo.get (Position);
          Imageview image = (imageview) view.findViewByid (r.id.icon);
          image.setImagedrawable (res.Loadicon (context.getpackagemanager ()));
          TextView TextView = (TextView) view.findViewByid (R.ID.title);
          textLabel (Context.getPackagemanager ()). Tostring ());
          Return.
              view;
        }
      };
    }
  // ================================================ =============
    / **
     * Get Absolute Path of the File From It's URI
     *
     * @Param Context Context from Your Activity.
     * @param Contenturi Uri of the File.
     * @return Absolute Path Of the File
     * /
    Public Static String GetRealpathFromuri (Context CONTEXT, URI Contenturi) {
      STRING RESULT = NULL;
      Cursor Cursor = context.getContentResolver (). Query (Contenturi, Null, Null, NULL, NULL);
      If (Cursor == NULL) {// Source IS Dropbox or Other Similar Local File Path
        result = contenturi.getpath ();
      } else {
        cursor.movetofirst ();
        int iDx = Cursor.Getcolumnindex (mediastore.images.imagecolumns.data);
        if (idx & gt; = 0) {
          Result = Cursor.getString (IDX);
        }
        cursor.close ();
      }
      RETURN RESULT;
    }
    Public Static Bitmap ScaleImageFile (File F) {
      Try {
  // Decode Image Size
        Bitmapfactory.options o = new bitmapfactory.options ();
        O.INJUSTDECODEBOUNDS = TRUE;
        Bitmapfactory.decodestream (New FileInputStream (F), NULL, O);
  // The New Size We Want to Scale To
        Final int required_size = 300;
  // Find The Correct Scale Value. IT SHOLD BE THE POWER OF 2.
        int scale = 1;
        While (O.Outwidth / Scale / 2 & GT; = Required_size & amp; & amp;
            O.outheight / Scale / 2 & gt; = required_size) { 
scale * = 2;
        }
  // Decode with InsampleSize
        Bitmapfactory.options O2 = New BitmapFactory.Options ();
        O2.InsampleSize = scale;
        return bitmapfactory.decodestream (new fileinputstream (F), NULL, O2);
      } Catch (FileNotFoundException E) {
        E.PrintStackTrace ();
      }
      RETURN NULL;
    }
    // Storage Permissions
    Private Static Final int Request_external_storage = 1;
    Private Static String [] permissions_storage = {
        Manifest.permission.read_external_storage,
        Manifest.permission.write_external_storage
    };
    / **
     * Checks If The App Has Permission to Write to Device Storage
     *
     * If The App Does Not Has Permission Thene The User Will Be Prompted to Grant Permissions
     *
     * @Param Activity
     * /
    Public Static Void VerifyStoragePermissions (Activity Activity) {
  // Check If We Have Write Permission
      int permission = ActivityCompat.checkSelfpermission (Activity, manifest.permission.write_external_storage);
      If (permission! = packagemanager.permission_granted) {
  // We Don't Have Permission SO Prompt The User
        ActivityCompat.Requestpermissions (
            Activity
            PERMISSIONS_STORAGE,
            Request_External_storage
        );
      }
    }
  }

Answer 2

Similar problem.
Deleting a string

Android: nohistory = "True"

From the description of Activity solved the problem

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions