"Android" reads all the pictures on the SDcard card and shows that the reading process has a progress bar display

Source: Internet
Author: User

Although the following app has not done fast map browsing, ES file browser level, encounter big sdcard or there will be read too long, memory overflow and other issues, but the basic idea is this.

For example, there are 4 pictures on the SDcard card,


Open the app, then all the pictures on the SD card are read and displayed, and the reading process has a progress bar display.


The production process is as follows:

1, first, res\values\strings.xml to the character set as follows, nothing special.

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <string name= "App_name" > Read all pictures under SDcard </string>    <string name= "action_settings" >Settings</string>    <string name= "Imageview_ Description "> Big picture </string>  </resources>
2, after, modified res\layout\activity_main.xml form layout, here using the layout and "Android" gallery-style picture browser, using Horizontalscrollview instead of gallery, Onclicklistener parameter Transfer (click the Open link) is exactly the same, but here, Horizontalscrollview's linearlayout instead of Java code generation, Therefore, the ID is given to Horizontalscrollview.

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:layout_width= "Match_ Parent "    android:layout_height=" match_parent "    android:orientation=" vertical ">    <imageview        Android:id= "@+id/imageview1"        android:layout_width= "match_parent"        android:layout_height= "200DP        " android:contentdescription= "@string/imageview_description"        android:paddingtop= "10DP"/>    < Horizontalscrollview        android:id= "@+id/horizontalscrollview1"        android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:layout_gravity= "center_vertical"        android: scrollbars= "Horizontal" >    </HorizontalScrollView></LinearLayout>

3, then, and "Android" read sdcard on the picture (click the Open link), androidmanifest.xml insert <uses-permission android:name= " Android.permission.READ_EXTERNAL_STORAGE "/> and <uses-permission android:name=" android.permission.WRITE_ External_storage "/> requires permission to read and write to SDcard, this file is modified as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Com.example.asyncread "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" android.pe Rmission. Read_external_storage "/> <!--require data access to SDcard and <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/> <!--required to write data to SDcard permissions--<application Android:allowbac Kup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@styl E/apptheme "> <activity android:name=" com.example.asyncread.MainActivity "Android:label = "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MA In "/> <category android:name=" andRoid.intent.category.LAUNCHER "/> </intent-filter> </activity> </application>&lt ;/manifest>
4, in the end, is the key to the whole process, the preparation of Mainactivity.java. Here first insert two tool class, one in "Java" read all folders and files under the path "(click Open link) said, used to traverse sdcard above the file, of course, when the traversal of the SDcard Android this system folder, Do not remove the words will be the system's icon and so on to traverse out. Then there is a picture scaling class that does not scale the read to a memory overflow error when the app is running.

At the beginning of the program, in the OnCreate method, a progress bar is generated on the app's head, and then the asynchronous class Asynctask is called to read the SDcard card file, with "Android" gallery-style picture browser, Use the Horizontalscrollview instead of the Gallery,onclicklistener parameter transfer (click the Open link) in the same way, the picture resource is loaded out of a sheet. Just the object from the app's picture resource, into a picture read from SDcard.

Package Com.example.asyncread;import Java.io.file;import Java.util.arraylist;import android.os.asynctask;import Android.os.bundle;import Android.os.environment;import Android.view.gravity;import Android.view.View;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.view.window;import Android.widget.horizontalscrollview;import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.linearlayout.layoutparams;import Android.widget.textview;import Android.app.Activity;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;public class Mainactivity extends Activity {// Android Components private Horizontalscrollview horizontalscrollview1;private ImageView imageview1;//for storing all picture paths on the SDcard card public static arraylist<string> Dirallstrarr = new arraylist<string> ()//class public static void for traversing all files on the SDcard card Dirall (file dirfile) throws Exception {if (dirfile.exists ()) {File files[] = Dirfile.listfiles (); for (file file:files) { if (fIle.isdirectory ()) {String fileName = File.getname ();//except SDcard on Android this folder. if (!filename.endswith ("Android")) {//If a folder is encountered, it is called recursively. Dirall (file);}} else {//If the picture file is pressed into the array string fileName = File.getname (); if (Filename.endswith (". jpg") | | filename.endswith (". jpeg") | | Filename.endswith (". bmp") | | Filename.endswith (". gif") | | Filename.endswith (". png")) {//If a file is encountered, put the array if (Dirfile.getpath (). EndsWith (File.separator)) {Dirallstrarr.add ( Dirfile.getpath () + file.getname ());} else {Dirallstrarr.add (Dirfile.getpath () + file.separator+ file.getname ());}}}}} Picture loaded class public static bitmapfactory.options getheapopts (file file) {Bitmapfactory.options opts = new Bitmapfactory.options ();//The larger the number read out the heap must be smaller, or it will always overflow if (File.length () < 20480) {//0-20kopts.insamplesize = 1;// This means scaled size} else if (File.length () < 51200) {//20-50kopts.insamplesize = 2;} else if (File.length () < 307200) {// 50-300kopts.insamplesize = 4;} else if (File.length () < 819200) {//300-800kopts.insamplesize = 6;} else if(File.length () < 1048576) {//800-1024kopts.insamplesize = 8;} else {opts.insamplesize = 10;} return opts;} Class MyTask extends Asynctask<void, Integer, linearlayout> {@Override//What to do before the task starts protected Void OnPreExecute () { Setprogressbarvisibility (TRUE);//Show Progress bar Super.onpreexecute ();} @Overrideprotected linearlayout doinbackground (Void ... arg0) {//Generate a horizontal layout linearlayout linearLayout1 = new LinearLayout (Mainactivity.this); Layoutparams layoutparams = new Layoutparams (VIEWGROUP.LAYOUTPARAMS.WRAP_CONTENT,VIEWGROUP.LAYOUTPARAMS.WRAP_ CONTENT); linearlayout1.setorientation (linearlayout.horizontal); Linearlayout1.setlayoutparams (layoutParams);// Apply to the newly generated linear layout */* Traverse all folders owned by SDcard start */string Sdpath = Environment.getexternalstoragedirectory (). GetAbsolutePath ();// Gets the root path of the SDcard file Dirfile = new file (Sdpath); try {dirall (dirfile);} catch (Exception e) {e.printstacktrace ();}  /* Iterate through all of the SDcard's folders *///get all the picture paths from SDcard, then iterate over the array for (int i = 0; i < dirallstrarr.size (); i++) {String FilePath = DiraLlstrarr.get (i); File File = new file (FilePath); Bitmap BM = bitmapfactory.decodefile (filepath,getheapopts (file)); LinearLayout linearLayout2 = new LinearLayout (mainactivity.this);//Set the parameters for the newly generated linear layout, width 100, height to match the parent component, That is, the height of the horizontal scrolling view layoutparams layoutParams1 = new Layoutparams (100,viewgroup.layoutparams.match_parent); Layoutparams1.gravity = gravity.center_horizontal;//Sets the horizontal center of the component within the linear layout linearlayout2.setorientation ( linearlayout.vertical);//Set the newly generated linear layout android:orientation= "VERTICAL" Linearlayout2.setlayoutparams (LAYOUTPARAMS1) ;//applied to the newly generated linear layout ImageView imageView2 = new ImageView (mainactivity.this); Imageview2.setid (i + 20000);//here because the ID cannot be a character, All image IDs are set to 20000,20001,20002,... Easy to click on the image below the Listener control Imageview2.setimagebitmap (BM);//Put the image of the image in the array in Picture View Imageview2.setadjustviewbounds (TRUE);// Auto Scale to Imageview2.setmaxheight (80);//The height of the picture is 80dpimageview2.setpadding (10, 10, 10, 10); Imageview2.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (view view) {String FilePath = Dirallstrarr.get (View.getid ()-20000); File File = new file (FilePath); Bitmap BM = bitmapfactory.decodefile (filepath,getheapopts (file)); Imageview1.setimagebitmap (BM);//When the image ID of the click is removed, Minus 20000 is the position of the image to be displayed in the image array. });//load the picture view into the newly generated linear layout linearlayout2.addview (IMAGEVIEW2);//New to a label text TextView TextView = new TextView ( Mainactivity.this); Textview.settext (FilePath); textview.settextsize (15);//Label text centered in horizontal position textview.setgravity ( Gravity.center);//Added to the newly generated linear layout after Linearlayout2.addview (TextView); Linearlayout1.addview (LINEARLAYOUT2); Publishprogress (i);//Call onprogressupdate method}return linearLayout1;} @Overrideprotected void Onprogressupdate (Integer ... values) {setprogress (values[0] * 2500);// Update progress bar super.onprogressupdate (values);} @overrideprotected void OnPostExecute (linearlayout result) {setprogressbarvisibility (false) after the task is put out; Horizontalscrollview1.addview (result);//Put Doinbackground () to the horizontal layout of the horizontal scrolling layout super.onpostexecute (result);}} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); RequestwindowfeaTure (window.feature_progress);//Generate a progress bar in the head, which must be in Setcontentview (R.layout.activity_main); Before this statement Setcontentview ( R.layout.activity_main);//get various components HorizontalScrollView1 = (Horizontalscrollview) Findviewbyid ( R.ID.HORIZONTALSCROLLVIEW1); imageView1 = (ImageView) Findviewbyid (r.id.imageview1); new MyTask (). Execute ();// Start MyTask Task}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" reads all the pictures on the SDcard card and shows that the reading process has a progress bar display

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.