"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 with. There are 4 pictures on the SDcard card,


Open the app and it will read all the pictures on the SD card and display it. The read process has a progress bar display.


The production steps are as follows:

1, first, res\values\strings.xml to character settings such as the following, 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 the change Res\layout\activity_main.xml form layout, here with the layout and "Android" gallery-style picture browser, using Horizontalscrollview instead of gallery. Onclicklistener (click to open link) is exactly the same, just 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. Same as "Android" reading the picture on SDcard (click to open link). Insert <uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/> and < in Androidmanifest.xml Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> requires permission to read and write to SDcard. This file changes after the following example:

<?

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 androi d:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permission.REA D_external_storage "/> <!--required to read data to SDcard permissions--<uses-permission android:name=" android.permission.WRITE_ External_storage "/> <!--required to write data to SDcard permissions--<application android:allowbackup=" true "Android : icon= "@drawable/ic_launcher" android:label= "@string/app_name" android:theme= "@style/apptheme" > & Lt;activity android:name= "com.example.asyncread.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></man Ifest>

4, in the end, is the key to the whole process, the preparation of Mainactivity.java. Here we first insert two tool classes, one in "Java" read all directories and files under the path (click the open link) said. Used to traverse the file above the SDcard, of course, when traversing the SDcard on Android this system directory. Do not remove the words will be the system's icon and so on to traverse out. After that is a picture scaling class. The image is not read correctly to zoom in. A memory overflow error occurs while the app is executing.

At the beginning of the program, in the OnCreate method, a progress bar is generated on the app's head. The asynchronous class Asynctask is then called to read the SDcard card file. Like the "Android" gallery-style picture browser, use Horizontalscrollview instead of Gallery,onclicklistener (click to open the link) in the same way, the picture resources are loaded into a sheet.

It is just a function object from the app's picture resource. It becomes 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 directory. if (!filename.endswith ("Android")) {//assumes that the directory is encountered recursively called.

Dirall (file);}} else {//Suppose 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")) {//Assuming that the file is encountered is placed in 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-102 4kopts.insamplesize = 8;} else {opts.insamplesize = 10;} return opts;} Class MyTask extendsAsynctask<void, Integer, linearlayout> {@Override//What to do before the task starts protected Void OnPreExecute () { Setprogressbarvisibility (TRUE);//Display Run 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 directories under SDcard to 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 SDcard's directory end *///get all of SDcard's picture paths, then iterate over this 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);//sets the parameters of the newly generated linear layout. Width is 100, height is matched to parent component, which 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 in 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);//The image in the array is placed in the picture view Imageview2.setadjustviewbounds (true); Self-scaling to the aspect ratio 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), minus 20000 is the position of the image to be displayed in the image array after the clicked Image ID is removed.

});//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, must be in Setcontentview (R.layout.activity_main); This statement precedes 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}}



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

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.