{"id":1433,"date":"2022-08-30T15:16:29","date_gmt":"2022-08-30T15:16:29","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/16\/android-let-user-pick-capture-photo-from-gallery-or-camera-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:16:29","modified_gmt":"2022-08-30T15:16:29","slug":"android-let-user-pick-capture-photo-from-gallery-or-camera-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/android-let-user-pick-capture-photo-from-gallery-or-camera-collection-of-common-programming-errors\/","title":{"rendered":"Android let user pick\/capture photo from gallery or camera-Collection of common programming errors"},"content":{"rendered":"<p>I want to that when a user clicks a button, he can choose gallery or camera, and that the program can retrieve the captured\/picked photo. I tried a couple of things, but nothing seems to work completely. This is how I start the gallery so the user can pick a photo:<\/p>\n<pre><code>    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);\n    startActivityForResult(i,3);\n<\/code><\/pre>\n<p>And this is how I try to retrieve the by the user picked photo:<\/p>\n<pre><code>        Uri selectedImage = data.getData();\n\n        filename = \"NEWIMAGE\";\n        String[] filePathColumn = { MediaStore.Images.Media.DATA };\n\n        Cursor cursor = getContentResolver().query(selectedImage,\n                filePathColumn, null, null, null);\n        cursor.moveToFirst();\n\n        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);\n        String picturePath = cursor.getString(columnIndex);\n        cursor.close();\n        final int REQUIRED_SIZE=70;\n        int scale = 1;\n        BitmapFactory.Options options = new BitmapFactory.Options();\n        if (options.outHeight &gt; REQUIRED_SIZE || options.outWidth &gt; REQUIRED_SIZE) {\n            scale = (int)Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE \/ \n               (double) Math.max(options.outHeight, options.outWidth)) \/ Math.log(0.5)));\n        }\n\n        options.inJustDecodeBounds = true;\n        options.inSampleSize = scale;           \n        photo = BitmapFactory.decodeFile(picturePath, options);\n<\/code><\/pre>\n<p>The error when I run it:<\/p>\n<pre><code>E\/AndroidRuntime(21260): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=3, result=-1, data=Intent { dat=content:\/\/media\/external\/images\/media\/2449 }} to activity {com.aquariumzoekenpro.android\/com.aquariumzoekenpro.android.LogboekNotitie}: java.lang.NullPointerException\nE\/AndroidRuntime(21260):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3000)\nE\/AndroidRuntime(21260):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3043)\nE\/AndroidRuntime(21260):    at android.app.ActivityThread.access$1100(ActivityThread.java:127)\nE\/AndroidRuntime(21260):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1188)\nE\/AndroidRuntime(21260):    at android.os.Handler.dispatchMessage(Handler.java:99)\nE\/AndroidRuntime(21260):    at android.os.Looper.loop(Looper.java:137)\nE\/AndroidRuntime(21260):    at android.app.ActivityThread.main(ActivityThread.java:4441)\nE\/AndroidRuntime(21260):    at java.lang.reflect.Method.invokeNative(Native Method)\nE\/AndroidRuntime(21260):    at java.lang.reflect.Method.invoke(Method.java:511)\nE\/AndroidRuntime(21260):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)\nE\/AndroidRuntime(21260):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)\nE\/AndroidRuntime(21260):    at dalvik.system.NativeStart.main(Native Method)\nE\/AndroidRuntime(21260): Caused by: java.lang.NullPointerException\nE\/AndroidRuntime(21260):    at com.aquariumzoekenpro.android.LogboekNotitie.onActivityResult(LogboekNotitie.java:1483)\nE\/AndroidRuntime(21260):    at android.app.Activity.dispatchActivityResult(Activity.java:4649)\nE\/AndroidRuntime(21260):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2996)\nE\/AndroidRuntime(21260):    ... 11 more\n<\/code><\/pre>\n<p>Capturing a photo with the camera and retrieving also fails. This is how I start the camera:<\/p>\n<pre><code>    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);     \n    String filename = \"NEWIMAGE1\";\n    imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+\"\/\"+filename));\n    i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);\n    startActivityForResult(i,2);\n<\/code><\/pre>\n<p>And this is how I try to retrieve the captured photo:<\/p>\n<pre><code>String filename = \"NEWIMAGE1\";\nString urifilename = filename + \".jpg\";\nimageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+\"\/\"+urifilename));\nthis.getContentResolver().notifyChange(imageUri, null);\nContentResolver cr = this.getContentResolver();     \nphoto = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);\n<\/code><\/pre>\n<p>The error I get from the logcat:<\/p>\n<pre><code>W\/dalvikvm(21424): threadid=1: thread exiting with uncaught exception (group=0x40abc210)\nE\/AndroidRuntime(21424): FATAL EXCEPTION: main\nE\/AndroidRuntime(21424): java.lang.OutOfMemoryError\nE\/AndroidRuntime(21424):    at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)\nE\/AndroidRuntime(21424):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:499)\nE\/AndroidRuntime(21424):    at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:555)\nE\/AndroidRuntime(21424):    at android.provider.MediaStore$Images$Media.getBitmap(MediaStore.java:710)\nE\/AndroidRuntime(21424):    at com.aquariumzoekenpro.android.LogboekNotitie.onActivityResult(LogboekNotitie.java:1429)\nE\/AndroidRuntime(21424):    at android.app.Activity.dispatchActivityResult(Activity.java:4649)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2996)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2451)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2492)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1997)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3371)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.access$700(ActivityThread.java:127)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1162)\nE\/AndroidRuntime(21424):    at android.os.Handler.dispatchMessage(Handler.java:99)\nE\/AndroidRuntime(21424):    at android.os.Looper.loop(Looper.java:137)\nE\/AndroidRuntime(21424):    at android.app.ActivityThread.main(ActivityThread.java:4441)\nE\/AndroidRuntime(21424):    at java.lang.reflect.Method.invokeNative(Native Method)\nE\/AndroidRuntime(21424):    at java.lang.reflect.Method.invoke(Method.java:511)\nE\/AndroidRuntime(21424):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)\nE\/AndroidRuntime(21424):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)\nE\/AndroidRuntime(21424):    at dalvik.system.NativeStart.main(Native Method)\n<\/code><\/pre>\n<p>So I want to let the user choose to either pick an image from the gallery or to capture a photo with the camera. Then I want the program to get the picked or captured image in the original quality, so I can show it in an Imageview or something.<\/p>\n<p>Thanks in advance,<\/p>\n<p>Simon<\/p>\n<ol>\n<li>\n<p>Simon, I have this working for picking from the gallery using this intent:<\/p>\n<pre><code>Intent intent = new Intent(Intent.ACTION_GET_CONTENT);\nintent.setType(\"image\/*\");\n<\/code><\/pre>\n<p>And then handling the choice like this:<\/p>\n<pre><code>  mFilename=null;\n  mPath=null;\n\n  Uri selectedImage = data.getData();\n  final String[] filePathColumn = { MediaColumns.DATA, MediaColumns.DISPLAY_NAME };\n  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);\n\n  \/\/ some devices (OS versions return an URI of com.android instead of com.google.android \n  if (selectedImage.toString().startsWith(\"content:\/\/com.android.gallery3d.provider\"))  \n  {\n      \/\/ use the com.google provider, not the com.android provider. \n      selectedImage = Uri.parse(selectedImage.toString().replace(\"com.android.gallery3d\",\"com.google.android.gallery3d\"));\n  }\n\n  if (cursor != null) {\n      cursor.moveToFirst();\n      int columnIndex = cursor.getColumnIndex(MediaColumns.DATA);\n\n      \/\/ if it is a picasa image on newer devices with OS 3.0 and up\n      if (selectedImage.toString().startsWith(\"content:\/\/com.google.android.gallery3d\"))\n      {\n          columnIndex = cursor.getColumnIndex(MediaColumns.DISPLAY_NAME);\n          if (columnIndex != -1)\n          {\n              final Uri uriurl = selectedImage;\n              \/\/ should do this in a background thread, since we are fetching a large image from the web\n              mFilename = getGalleryFile(activity, uriurl);\n          }\n      }\n      else\n      {\n          \/\/ it is a regular local image file\n          String filePath = cursor.getString(columnIndex);\n          cursor.close();\n          mFilename = filePath;\n      }\n  }\n  \/\/ If it is a picasa image on devices running OS prior to 3.0\n  else if (selectedImage != null &amp;&amp; selectedImage.toString().length() &gt; 0)\n  {\n      final Uri uriurl = selectedImage;\n      \/\/ should do this in a background thread, since we are fetching a large image from the web\n      mFilename = getGalleryFile(activity, uriurl);\n   }\n<\/code><\/pre>\n<p>And as for the camera part of what you want, what you&#8217;re doing looks fine you are just running out of memory creating the Bitmap. You should use BitmapFactory::decodeStream with BitmapFactory.Options set to scale the incoming image to the size of the View you&#8217;re going to display it in.<\/p>\n<p>As explained below, to complete the answer here is getGalleryFile:<\/p>\n<pre><code>public static String getGalleryFile(Activity activity, Uri url)\n{\n    String fileName=null;\n    File path;\n\n    try {\n        \/\/ getCameraStoragePath is a function in my activity\n        \/\/ that returns a location where I'm writing files\n        \/\/ you could use Environment.getExternalStorageDirectory()\n        \/\/ or ....\n        path = new File(MyTask.getCameraStoragePath());\n    } catch (Exception e1) {\n        \/\/ todo: handle exception\n        return null;\n    }\n\n    SimpleDateFormat timeStampFormat = new SimpleDateFormat(\"yyyyMMddHHmmssSS\");\n    fileName = \"gallery.\" + timeStampFormat.format(new java.util.Date()) + \".jpg\";\n    File out = new File(path, fileName);\n\n    try {\n        InputStream is = null;\n        if (url.toString().startsWith(\"content:\/\/com.google.android.gallery3d\"))\n        {\n            is=activity.getContentResolver().openInputStream(url);\n        }\n        else\n        {\n            is=new URL(url.toString()).openStream();\n        }\n\n        OutputStream os = new FileOutputStream(out);\n\n        byte[] buffer = new byte[1024];\n        int len;\n        while ((len = is.read(buffer)) != -1)\n        {\n            os.write(buffer, 0, len);\n        }\n\n        os.close();\n        return out.getAbsolutePath();\n    }\n    catch (Exception ex)\n    {\n        \/\/ todo: handle exception\n        return null;\n    }\n}\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-16 20:52:27. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I want to that when a user clicks a button, he can choose gallery or camera, and that the program can retrieve the captured\/picked photo. I tried a couple of things, but nothing seems to work completely. This is how I start the gallery so the user can pick a photo: Intent i = new [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1433","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1433","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=1433"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1433\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=1433"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=1433"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=1433"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}