Android Combat Simple Tutorial-28th gun (URI to string instance)

Source: Internet
Author: User

The next article. We can easily get the URI of the selected image, so how do we consider converting the obtained URI to a string-type address?

Then we will study it by example. Layout file and the previous (27 gun) Consistent, we will no longer list, directly to see Mainactivity.java:

Package Com.example.userphoto;import Java.io.file;import Android.app.activity;import android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.drawable.bitmapdrawable;import Android.graphics.drawable.drawable;import Android.net.uri;import Android.os.bundle;import android.os.Environment; Import Android.provider.mediastore;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;import Android.widget.toast;import Cn.bmob.v3.Bmob;import Cn.bmob.v3.datatype.bmobfile;import Cn.bmob.v3.listener.uploadfilelistener;public class MainActivity extends Activity implements Onclicklistener {private static final int image_request_code = 0;private static final int camera_reque St_code = 1;private static final int resize_request_code = 2;private static final String image_file_name = "Header.jpg";p R Ivate ImageView mimageheader; @Overrideprotected void OnCreate (Bundle savedinstancestate){super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Bmob.initialize (This, "8f3ffb2658d8a3366a70a0b0ca0b71b2");//Initialize Bmobsetupviews ();} private void Setupviews () {Mimageheader = (ImageView) Findviewbyid (R.id.image_header); final Button selectBtn1 = (Button) Findviewbyid (r.id.btn_selectimage); final Button selectBtn2 = (Button) Findviewbyid (R.id.btn_takephoto); Selectbtn1.setonclicklistener (this); Selectbtn2.setonclicklistener (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.btn_selectimage:intent galleryintent = new Intent (Int Ent. action_get_content); galleryintent.addcategory (intent.category_openable); Galleryintent.settype ("image/*");// Picture Startactivityforresult (Galleryintent, Image_request_code); Break;case r.id.btn_takephoto:if (isSdcardExisting ()) {Intent cameraintent = new Intent ("Android.media.action.IMAGE_CAPTURE");//Photo Cameraintent.putextra (Mediastore.extra _output, Getimageuri ()); Cameraintent.putextra (mediastore.extra_video_quality, 0); StartaCtivityforresult (Cameraintent, Camera_request_code);} else {Toast.maketext (V.getcontext (), "Please insert SD card", Toast.length_long). Show (); Break;}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (ResultCode! = RESULT_OK) {Retu RN;} else {switch (requestcode) {case Image_request_code:uri originaluri=data.getdata ();//Get Picture Uriresizeimage (Originaluri )///The following method converts the obtained URI to a string type Oh! String []imgs={mediastore.images.media.data};//Converts the picture URI to a storage path Cursor cursor=this.managedquery (Originaluri, IMGs,  NULL, NULL, NULL);  int Index=cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA);  Cursor.movetofirst ();  String img_url=cursor.getstring (index); Showtoast (Img_url); Break;case camera_request_code:if (Issdcardexisting ()) {Resizeimage (GetImageUri ());/*// Upload picture String imgpath = Getimageuri (); final bmobfile icon = new Bmobfile (new File (Imgpath)); Icon.upload (this, new UploadFile Listener () {@Overridepublic void onsuccess () {//TODO auto-generated method Stubperson person = new Person ();p Erson.seticon (icon);p erson.save (mainactivity.this) showtoast ("image upload succeeded");} @Overridepublic void OnProgress (Integer arg0) {//TODO auto-generated method stub} @Overridepublic void OnFailure (int arg0 , String arg1) {//TODO auto-generated method Stubshowtoast ("Picture upload failed:" +ARG1);}); */} else {Toast.maketext (mainactivity.this, "No memory card found, no photos saved!

", Toast.length_long). Show ();} Break;case resize_request_code:if (data = null) {showresizeimage (data);} Break;}} Super.onactivityresult (Requestcode, ResultCode, data);} private void Showtoast (String msg) {Toast.maketext (this, MSG, Toast.length_short). Show (); Private Boolean issdcardexisting () {//infers if the SD card has a final String state = Environment.getexternalstoragestate (); State.equals (environment.media_mounted)) {return true;} else {return false;}} public void Resizeimage (URI uri) {//Reshape picture size intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, "image/*"); Intent.putextra ("Crop", "true");//ability to crop Intent.putextra ("Aspectx", 1); Intent.putextra ("Aspecty", 1), Intent.putextra ("Outputx", "Intent.putextra"; Return-data ", true); Startactivityforresult (Intent, resize_request_code);} private void Showresizeimage (Intent data) {//Display picture Bundle extras = Data.getextras (); if (extras! = null) {Bitmap photo = Extr As.getparcelable ("Data");D rawable drawable = New bitmapdrawable (photo); mimageheader.setimagedrawable (drawable);}} Private Uri Getimageuri () {//Get path return Uri.fromfile (New File (Environment.getexternalstoragedirectory (), Image_file_ NAME));}}


To list the methods separately is:

                                Uri Originaluri=data.getdata ();//Get Picture Uriresizeimage (Originaluri);//The following method converts the obtained URI to a string type Oh! String []imgs={mediastore.images.media.data};//Converts the picture URI to the storage path  Cursor cursor=this.managedquery (Originaluri, IMGs, NULL, NULL, NULL);  int Index=cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA);  Cursor.movetofirst ();  String img_url=cursor.getstring (index);  Showtoast (Img_url);

The execution instance will appear for example the following error:


Do not understand English may also be able to understand, prompt permission is insufficient, we add such as the following permissions:


Execute the example and successfully pass:


The path to the picture is shown in the toast, so what's the use of getting the path? Take a look at the next article (29 shots).



Welcome reprint, Praise, attention, thank you for your support!

Android Easy Tutorial-28th gun (URI to string instance)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.