android-upload or download images from your albums

Source: Internet
Author: User

Target effect:

Open the album to select a picture, will be displayed to the top of the ImageView and stored in the Bmob, after storage into the bmob background, copy the data just added Objectid, paste into the code specified out, and then run, click the download will show the image just uploaded in the imageview below , here the download is specified Objectid, can be dynamically obtained objectid for download.


1.activity_main.xml Page Setup layout.

Activity_main.xml page:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:context =". Mainactivity "><imageview android:id=" @+id/ivhead "android:layout_margintop=" 20DP "Android:layout_centerHo Rizontal= "true" android:layout_width= "150DP" android:layout_height= "150DP"/><button android:id= "@+id/btnSel Ectimage "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layout_alignParentLeft    = "true" android:layout_below= "@+id/ivhead" android:layout_margintop= "16DP" android:text= "open album"/><button Android:id= "@+id/btndownloadimage" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android Oid:layout_alignparentleft= "true" android:layout_below= "@+id/btnselectimage" android:text= "Download Picture"/>< ImageView android:id= "@+id/ivdownload" Android: layout_width= "150DP" android:layout_height= "150DP" android:layout_margintop= "20DP" Android:layout_centerhorizont Al= "true" android:layout_below= "@+id/btndownloadimage"/></relativelayout>


2.mainactivity.java page definition upload and download method. Mainactivity.java page:
Package Com.example.text;import Java.io.file;import Cn.bmob.v3.bmob;import cn.bmob.v3.bmobquery;import Cn.bmob.v3.datatype.bmobfile;import Cn.bmob.v3.listener.downloadfilelistener;import Cn.bmob.v3.listener.getlistener;import Cn.bmob.v3.listener.uploadbatchlistener;import Cn.bmob.v3.listener.uploadfilelistener;import Com.android.volley.toolbox.imageloader;import Com.example.text.mainactivity;import entity. Person;import Android.net.uri;import Android.os.bundle;import Android.os.environment;import Android.provider.mediastore;import Android.app.activity;import Android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.drawable.bitmapdrawable;import Android.graphics.drawable.drawable;import Android.view.View; Import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.imageview;import Android.widget.toast;public class Mainactivity extends Activity implements OnclicklisteneR {Private ImageView ivhead, Ivdownload;private Button btnselectimage, btndownloadimage;private static final int Image_co DE = 0;//Open album private static final int resize_code = 2;//Resize private static final string image_name = "";//Picture String @overri deprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Bmob.initialize (This, "8ef8a4752f48682eadb32d3c8c8e398f");//Initialize bmob//initialization control init ();//Bind Sentinel Event Bindclick ();} Initialize the control private void init () {ivhead = (ImageView) Findviewbyid (r.id.ivhead); ivdownload = (ImageView) Findviewbyid ( R.id.ivdownload) Btnselectimage = (Button) Findviewbyid (r.id.btnselectimage); btndownloadimage = (Button) Findviewbyid (r.id.btndownloadimage);} Bind a fixed-point event private void Bindclick () {Btnselectimage.setonclicklistener (this); Btndownloadimage.setonclicklistener ( this);} @Overridepublic void OnClick (view view) {switch (View.getid ()) {case R.id.btnselectimage:intent galleryintent = new Inten T (intent.action_get_content);Galleryintent.addcategory (intent.category_openable); Galleryintent.settype ("image/*");//   Picture Startactivityforresult (Galleryintent, Image_code); Jump, pass open album request code break;case r.id.btndownloadimage:bmobquery<person> query=new bmobquery<person> (); Query.getobject (This, "Ef292ff6ef", new getlistener<person> () {// The second parameter is objectid@overridepublic void onsuccess (person person) {Toast.maketext (Mainactivity.this, ") for the Bmobfile data you want to download. Get Success ", Toast.length_short). Show ();//Download Picture downloadimage (person);} @Overridepublic void onfailure (int arg0, String arg1) {toast.maketext (Mainactivity.this, "Get Failed", Toast.length_short). Show ();}}); Break;default:break;}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (ResultCode! = RESULT_OK) {Retu RN;} else {switch (requestcode) {case Image_code:uri URI = Data.getdata (); Resizeimage (URI);//Convert the obtained URI to string string[] Images = {MediaStore.Images.Media.DATA};//converts the picture URI to a storage path cursor cursor = This.managedquery (URI, images, null, NULL, NULL); int index = Cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA); Cursor.movetofirst (); String Img_url = cursor.getstring (index); upload (img_url); break;case resize_code:if (data = null) {Showresizeimage ( data);} Break;}} Super.onactivityresult (Requestcode, ResultCode, data);} Determine if the SD card exists private Boolean issdcardexisting () {final String state = Environment.getexternalstoragestate (); if ( State.equals (environment.media_mounted)) {return true;} else {return false;}} Reshape picture size public void Resizeimage (Uri uri) {Intent Intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, "image/*"); Intent.putextra ("Crop", "true");//Can Crop Intent.putextra ("Aspectx", 1); Intent.putextra ("Aspecty", 1), Intent.putextra ("Outputx", "Intent.putextra"; Return-data ", true); Startactivityforresult (Intent, resize_code);//jump, pass resize request code}//get path Private Uri Getimageuri () { Return Uri.fromfile (New File (Environment.getexternalstoragedirectory (), image_name));} Show picturesprivate void Showresizeimage (Intent data) {Bundle extras = Data.getextras (); if (extras! = null) {Bitmap photo = Extras.get Parcelable ("Data");D rawable drawable = new bitmapdrawable (photo); ivhead.setimagedrawable (drawable);}} Image upload private void upload (String imgpath) {final bmobfile icon = new Bmobfile (new File (Imgpath)); Icon.upload (this, new up Loadfilelistener () {@Overridepublic void onsuccess () {Person person = new person ();p Erson.seticon (icon);p Erson.save ( Mainactivity.this); Toast.maketext (mainactivity.this, "image upload succeeded", Toast.length_short). Show (); @Overridepublic void onfailure (int arg0, String arg1) {toast.maketext (mainactivity.this, "picture upload failed", Toast.length_short) . Show ();}}); Download picture private void downloadimage (person person) {Bmobfile icon=person.geticon (); Icon.download (mainactivity.this,new Downloadfilelistener () {@Overridepublic void onsuccess (String url) {ivdownload.setimagebitmap (   Bitmapfactory.decodefile (URL)); Decode and display pictures based on address} @Overridepublic void onfailure (int arg0, String arg1) {toast.maKetext (mainactivity.this, "Download Failed", Toast.length_short). Show ();}});}} 


The 3.person.java page is an entity class, and the run automatically generates a person table that has only one field to store the picture. Person.java page:
Package Entity;import Cn.bmob.v3.bmobobject;import Cn.bmob.v3.datatype.bmobfile;public class Person extends Bmobobject{private bmobfile icon;public bmobfile GetIcon () {return icon;} public void SetIcon (bmobfile icon) {This.icon = icon;}}


4. Because Bmob is used, you need to add permissions. Androidmanifest.xml page:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.text "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permiss Ion. Write_contacts "/> <uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/> < Uses-permission android:name= "Android.permission.INTERNET"/> <!--allow Networking--<uses-permission android: Name= "Android.permission.INTERNET"/> <!--get information on network status such as GSM (2g), WCDMA (Unicom 3g) and <uses-permission Android:na Me= "Android.permission.ACCESS_NETWORK_STATE"/> <!--get information about the status of your WiFi network--<uses-permission android:name= "an Droid.permission.ACCESS_WIFI_STATE "/> <!--keep the CPU running, and the screen and keyboard lights may be turned off for file uploads and downloads--<uses-permission Androi  D:name= "Android.permission.WAKE_LOCK"/>  <!--get SD card Write permission for file upload and download--<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/&    Gt <!--allow read phone status to create Bmobinstallation---<uses-permission android:name= "Android.permission.READ_PHONE_STATE" /> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" Android:labe L= "@string/app_name" android:theme= "@style/apptheme" > <activity android:name= "com.example. Text. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest>


5. Note that before using Bmob, you need to download a third-party SDK, copy everything in the Libs folder to the Project Libs directory, and Properties->java Build path->libraries->add JARs ... Add the four jar packages you just copied



android-upload or download images from your albums

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.