Adv

How to load images from File System and render them

The concept covered here is loading of images from external storage or file system and rendering them in an adapterview like ListView or RecyclerView.

Share

Related Concepts

Adv

3 Examples

  1. Android FileSystem – GridView – Load Images from External Storage

    In this tutorial we see how to load images from extrnal storage into a custom ListView. We will render the images alongside the relative paths of spacecraft images.

    Those images are located in the downloads directory of our device or emulator.

    To load the individual images we use Picasso, probably the most popular image loader library out there. We will simply loop through that downloads folder and hold the files in a File array.

    Let’s go.

    1. Create Basic Activity Project

    1. First create a new project in android studio. Go to File –> New Project.
    2. Type the application name and choose the company name.
    3. Choose minimum SDK.
    4. Choose Basic activity.
    5. Click Finish.

    Basic activity will have a toolbar and floating action button already added in the layout

    Normally two layouts get generated with this option:

    No. Name Type Description
    1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
    2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
    3. MainActivity.java Class Main Activity.

    In this example I used a basic activity.

    The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

    If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

            <activity android_name=".MainActivity">
    
                <intent-filter>
    
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
    
                </intent-filter>
    
            </activity>
    

    You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

    Advantage of Creating Basic Activity project

    You can optionally choose empty activity over basic activity for this project.

    However basic activity has the following advantages:

    No. Advantage
    1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
    2. Provides us with appbar layout which implements material design appbar concepts.
    3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
    4. Decouples our custom content views and widgets from the templating features like toolbar.

    Generated Project Structure

    AndroidStudio will generate for you a project with default configurations via a set of files and directories.

    Here are the most important of them:

    No. File Major Responsibility
    1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
    2. libs/ To hold libraries we use in our project.
    3. src/main/ To hold the source code of our application.This is the main folder you work with.
    4. src/main/java/ Contains our java classes organized as packages.
    5. src/main/res/ Contains our project resources folders as follows.
    6. src/main/res/drawable/ Contains our drawable resources.
    7. src/main/res/layout/ Contains our layout resources.
    8. src/main/res/menu/ Contains our menu resources XML code.
    9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
    10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
    11. build.gradle Gradle Script used to build the android app.

    2. Build.gradle

    In our app level build.gradle we add Picasso library.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:24.1.1'
        compile 'com.android.support:design:24.1.1'
        compile 'com.android.support:cardview-v7:24.1.1'
        compile 'com.squareup.picasso:picasso:2.5.2'
    }
    

    3. Create User Interface

    User interfaces are typically created in android using XML layouts as opposed to direct java coding.

    This is an example of declarative programming.

    ######### Advantages of Using XML over Java

    No. Advantage
    1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
    2. It’s easily maintanable as the user interface is decoupled from your Java logic.
    3. It’s easier to share or download code and safely test them before runtime.
    4. You can use XML generated tools to generate XML

    Here are our layouts for this project:

    (a). activity_main.xml
    • This layout gets inflated to MainActivity user interface.
    • It includes the content_main.xml.

    Here are some of the widgets, views and viewgroups that get employed”

    No. View/ViewGroup Package Role
    1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
    2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
    3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
    4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_fitsSystemWindows="true"
        tools_context="com.tutorials.hp.gridviewimagessdcard.MainActivity">
    
        <android.support.design.widget.AppBarLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_theme="@style/AppTheme.AppBarOverlay">
    
            <android.support.v7.widget.Toolbar
                android_id="@+id/toolbar"
                android_layout_width="match_parent"
                android_layout_height="?attr/actionBarSize"
                android_background="?attr/colorPrimary"
                app_popupTheme="@style/AppTheme.PopupOverlay" />
    
        </android.support.design.widget.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
        <android.support.design.widget.FloatingActionButton
            android_id="@+id/fab"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_gravity="bottom|end"
            android_layout_margin="@dimen/fab_margin"
            android_src="@android:drawable/ic_dialog_email" />
    
    </android.support.design.widget.CoordinatorLayout>
    
    (b). content_main.xml

    This layout gets included in your activity_main.xml.
    We define our UI widgets here.

    We will define our gridview here.

    This GridView is what wil display our images from the external storage.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        app_layout_behavior="@string/appbar_scrolling_view_behavior"
        tools_context="com.tutorials.hp.gridviewimagessdcard.MainActivity"
        tools_showIn="@layout/activity_main">
    
        <GridView
            android_id="@+id/gv"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_numColumns="2" />
    </RelativeLayout>
    
    (c). model.xml

    This layout is our custom grid model. We need it because we want to render images and text in our GridView. This layout will get inflate in our CustomAdapter class.

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView 
        android_orientation="horizontal" android_layout_width="match_parent"
        
        android_layout_margin="10dp"
        card_view_cardCornerRadius="5dp"
        card_view_cardElevation="5dp"
        android_layout_height="200dp">
    
            <LinearLayout
                android_orientation="horizontal"
                android_layout_width="match_parent"
                android_layout_height="match_parent">
    
                <ImageView
                    android_id="@+id/spacecraftImg"
                    android_src="@drawable/placeholder"
                    android_layout_width="150dp"
                    android_layout_height="wrap_content" />
    
                <LinearLayout
                    android_orientation="vertical"
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content">
    
                    <TextView
                        android_layout_width="wrap_content"
                        android_layout_height="wrap_content"
                        android_textAppearance="?android:attr/textAppearanceLarge"
                        android_text="Name"
                        android_id="@+id/nameTxt"
                        android_padding="10dp"
                        android_textColor="@color/colorAccent"
                        android_textStyle="bold"
                        android_layout_alignParentLeft="true" />
    
                </LinearLayout>
    
            </LinearLayout>
    
    </android.support.v7.widget.CardView>

    4. Spacecraft.java

    We will be displaying Spacecraft images. So we need a POJO class to define how a Spacecraft looks in terms of properties.

    In this case our Spacecraft will have a name and an image URI.

    package com.tutorials.hp.gridviewimagessdcard;
    
    import android.net.Uri;
    
    public class Spacecraft {
    
        private String name;
        private Uri uri;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Uri getUri() {
            return uri;
        }
    
        public void setUri(Uri uri) {
            this.uri = uri;
        }
    }
    

    5. CustomAdapter.java

    This is our adapter class. This class derives from android.widget.BaseAdapter.

    This class will inflate our custom row model and bind data to resultant views. While Binding images we will use Picasso to load the image via their URIs.

    package com.tutorials.hp.gridviewimagessdcard;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.squareup.picasso.Picasso;
    
    import java.util.ArrayList;
    
    public class CustomAdapter extends BaseAdapter {
    
        Context c;
        ArrayList<Spacecraft> spacecrafts;
    
        public CustomAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
            this.c = c;
            this.spacecrafts = spacecrafts;
        }
    
        @Override
        public int getCount() {
            return spacecrafts.size();
        }
    
        @Override
        public Object getItem(int i) {
            return spacecrafts.get(i);
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
    
            if(view==null)
            {
                //INFLATE CUSTOM LAYOUT
                view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
            }
    
            final Spacecraft s= (Spacecraft) this.getItem(i);
    
            TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
            ImageView img= (ImageView) view.findViewById(R.id.spacecraftImg);
    
            //BIND DATA
            nameTxt.setText(s.getName());
            Picasso.with(c).load(s.getUri()).placeholder(R.drawable.placeholder).into(img);
    
            //VIEW ITEM CLICK
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(c, s.getName(), Toast.LENGTH_SHORT).show();
                }
            });
            return view;
        }
    }
    

    6. MainActivity.java

    As our activity this class will derive from android.support.v7.app.AppCompatActivity.

    This activity will be inflated from activity_main.xml. Our activity will basically be rendering a ListView.

    package com.tutorials.hp.gridviewimagessdcard;
    
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.GridView;
    
    import java.io.Console;
    import java.io.File;
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            final GridView gv= (GridView) findViewById(R.id.gv);
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    gv.setAdapter(new CustomAdapter(MainActivity.this,getData()));
                }
            });
        }
    
        private ArrayList<Spacecraft> getData()
        {
            ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
            //TARGET FOLDER
            File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    
            Spacecraft s;
    
            if(downloadsFolder.exists())
            {
                //GET ALL FILES IN DOWNLOAD FOLDER
                File[] files=downloadsFolder.listFiles();
    
                //LOOP THRU THOSE FILES GETTING NAME AND URI
                for (int i=0;i<files.length;i++)
                {
                    File file=files[i];
    
                    s=new Spacecraft();
                    s.setName(file.getName());
                    s.setUri(Uri.fromFile(file));
    
                    spacecrafts.add(s);
                }
            }
    
            return spacecrafts;
        }
    }
    

    7. AndroidManifest.xml

    This is our manifest file.

    We need to add the permission for reading from external storage here.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest 
        package="com.tutorials.hp.gridviewimagessdcard">
    
        <uses-permission android_name="android.permission.READ_EXTERNAL_STORAGE"/>
    
        <application
            android_allowBackup="true"
            android_icon="@mipmap/ic_launcher"
            android_label="@string/app_name"
            android_supportsRtl="true"
            android_theme="@style/AppTheme">
            <activity
                android_name=".MainActivity"
                android_label="@string/app_name"
                android_theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

    More Resources

    Resource Link
    GitHub Browse Browse
    GitHub Download Link Download

    Best Regards,
    Oclemy.

  2. Adv
  3. Android FileSystem – ListView – Load Images From External Storage

    This is an android filesystem tutorial. Our aim is to see how to load images from external storage, particularly from the downloads folder into our ListView.

    User clicks a button and we load those images into our ListView.

    Let’s go.

    1. Create Basic Activity Project

    1. First create a new project in android studio. Go to File –> New Project.
    2. Type the application name and choose the company name.
    3. Choose minimum SDK.
    4. Choose Basic activity.
    5. Click Finish.

    Basic activity will have a toolbar and floating action button already added in the layout

    Normally two layouts get generated with this option:

    No. Name Type Description
    1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
    2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
    3. MainActivity.java Class Main Activity.

    In this example I used a basic activity.

    The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

    If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

            <activity android_name=".MainActivity">
    
                <intent-filter>
    
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
    
                </intent-filter>
    
            </activity>

    You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

    Advantage of Creating Basic Activity project

    You can optionally choose empty activity over basic activity for this project.

    However basic activity has the following advantages:

    No. Advantage
    1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
    2. Provides us with appbar layout which implements material design appbar concepts.
    3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
    4. Decouples our custom content views and widgets from the templating features like toolbar.

    Generated Project Structure

    AndroidStudio will generate for you a project with default configurations via a set of files and directories.

    Here are the most important of them:

    No. File Major Responsibility
    1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
    2. libs/ To hold libraries we use in our project.
    3. src/main/ To hold the source code of our application.This is the main folder you work with.
    4. src/main/java/ Contains our java classes organized as packages.
    5. src/main/res/ Contains our project resources folders as follows.
    6. src/main/res/drawable/ Contains our drawable resources.
    7. src/main/res/layout/ Contains our layout resources.
    8. src/main/res/menu/ Contains our menu resources XML code.
    9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
    10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
    11. build.gradle Gradle Script used to build the android app.

    2. Build.gradle

    This is our app level build.gradle. We will be using Picasso imageloader library so we add it as a dependency.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:24.1.1'
        compile 'com.android.support:design:24.1.1'
        compile 'com.android.support:cardview-v7:24.1.1'
        compile 'com.squareup.picasso:picasso:2.5.2'
    }

    3. Create User Interface

    User interfaces are typically created in android using XML layouts as opposed by direct java coding.

    This is an example fo declarative programming.

    ######### Advantages of Using XML over Java

    No. Advantage
    1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
    2. It’s easily maintanable as the user interface is decoupled from your Java logic.
    3. It’s easier to share or download code and safely test them before runtime.
    4. You can use XML generated tools to generate XML

    Here are our layouts for this project:

    (a). activity_main.xml
    • This layout gets inflated to MainActivity user interface.
    • It includes the content_main.xml.

    Here are some of the widgets, views and viewgroups that get employed”

    No. View/ViewGroup Package Role
    1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
    2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
    3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
    4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_fitsSystemWindows="true"
        tools_context="com.tutorials.hp.listviewimagessdcard.MainActivity">
    
        <android.support.design.widget.AppBarLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_theme="@style/AppTheme.AppBarOverlay">
    
            <android.support.v7.widget.Toolbar
                android_id="@+id/toolbar"
                android_layout_width="match_parent"
                android_layout_height="?attr/actionBarSize"
                android_background="?attr/colorPrimary"
                app_popupTheme="@style/AppTheme.PopupOverlay" />
    
        </android.support.design.widget.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
        <android.support.design.widget.FloatingActionButton
            android_id="@+id/fab"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_gravity="bottom|end"
            android_layout_margin="@dimen/fab_margin"
            android_src="@android:drawable/ic_dialog_email" />
    
    </android.support.design.widget.CoordinatorLayout>
    (b). content_main.xml

    This layout gets included in your activity_main.xml.
    We define our UI widgets here.

    In this case the ListView to display our images from external storage:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        app_layout_behavior="@string/appbar_scrolling_view_behavior"
        tools_context="com.tutorials.hp.listviewimagessdcard.MainActivity"
        tools_showIn="@layout/activity_main">
        <ListView
            android_id="@+id/lv"
            android_layout_width="match_parent"
            android_layout_height="wrap_content" />
    </RelativeLayout>
    (b). model.xml

    We need a custom ListView to render our images from external storage alongside their paths, so we create a model layout that will help with that.
    This layout will be inflated into a custom row in our ListView:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView 
        android_orientation="horizontal" android_layout_width="match_parent"
        
        android_layout_margin="10dp"
        card_view_cardCornerRadius="5dp"
        card_view_cardElevation="5dp"
        android_layout_height="200dp">
            <LinearLayout
                android_orientation="horizontal"
                android_layout_width="match_parent"
                android_layout_height="match_parent">
    
                <ImageView
                    android_id="@+id/spacecraftImg"
                    android_src="@drawable/placeholder"
                    android_layout_width="150dp"
                    android_layout_height="wrap_content" />
    
                <LinearLayout
                    android_orientation="vertical"
                    android_layout_width="wrap_content"
                    android_layout_height="wrap_content">
                    <TextView
                        android_layout_width="wrap_content"
                        android_layout_height="wrap_content"
                        android_textAppearance="?android:attr/textAppearanceLarge"
                        android_text="Name"
                        android_id="@+id/nameTxt"
                        android_padding="10dp"
                        android_textColor="@color/colorAccent"
                        android_textStyle="bold"
                        android_layout_alignParentLeft="true" />
                </LinearLayout>
           </LinearLayout>
    </android.support.v7.widget.CardView>

    4. Spacecraft.java

    This is our model class, our data object.

    This class represents a single spacecraft object with it’s URI and name property. The URI leads us to the spacecraft’s image in our external storage.

    package com.tutorials.hp.listviewimagessdcard;
    
    import android.net.Uri;
    
    public class Spacecraft {
        private String name;
        private Uri uri;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Uri getUri() {
            return uri;
        }
    
        public void setUri(Uri uri) {
            this.uri = uri;
        }
    }

    5. CustomAdapter.java

    This is our adapter class, inheriting from android.widget.BaseAdapter.

    This class will inflate our model.xml layout and bind the spacecraft’s name and image onto it.

    To load images’ we’ll use Picasso.

    package com.tutorials.hp.listviewimagessdcard;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.squareup.picasso.Picasso;
    
    import java.util.ArrayList;
    
    public class CustomAdapter extends BaseAdapter {
    
        Context c;
        ArrayList<Spacecraft> spacecrafts;
    
        public CustomAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
            this.c = c;
            this.spacecrafts = spacecrafts;
        }
    
        @Override
        public int getCount() {
            return spacecrafts.size();
        }
    
        @Override
        public Object getItem(int i) {
            return spacecrafts.get(i);
        }
    
        @Override
        public long getItemId(int i) {
            return i;
        }
    
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if(view==null)
            {
                //INFLATE CUSTOM LAYOUT
                view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
            }
    
            final Spacecraft s= (Spacecraft) this.getItem(i);
    
            TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
            ImageView img= (ImageView) view.findViewById(R.id.spacecraftImg);
    
            //BIND DATA
            nameTxt.setText(s.getName());
            Picasso.with(c).load(s.getUri()).placeholder(R.drawable.placeholder).into(img);
    
            //VIEW ITEM CLICK
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(c, s.getName(), Toast.LENGTH_SHORT).show();
                }
            });
            return view;
        }
    }

    6. MainActivity.java

    This is our main activity class.

    It is our launcher activity. It will use the activity_main.xml as the layout.

    package com.tutorials.hp.listviewimagessdcard;
    
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.ListView;
    
    import java.io.File;
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            final ListView lv= (ListView) findViewById(R.id.lv);
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    lv.setAdapter(new CustomAdapter(MainActivity.this,getData()));
    
                }
            });
        }
    
        private ArrayList<Spacecraft> getData()
        {
            ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
            //TARGET FOLDER
            File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    
            Spacecraft s;
    
            if(downloadsFolder.exists())
            {
                //GET ALL FILES IN DOWNLOAD FOLDER
                File[] files=downloadsFolder.listFiles();
    
                //LOOP THRU THOSE FILES GETTING NAME AND URI
                for (int i=0;i<files.length;i++)
                {
                    File file=files[i];
    
                    s=new Spacecraft();
                    s.setName(file.getName());
                    s.setUri(Uri.fromFile(file));
    
                    spacecrafts.add(s);
                }
            }
    
            return spacecrafts;
        }
    }

    7. AndroidManifest.xml

    Add permission to read external storage in your androidmanifest.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest 
        package="com.tutorials.hp.listviewimagessdcard">
    
        <uses-permission android_name="android.permission.READ_EXTERNAL_STORAGE"/>
    
        <application
            android_allowBackup="true"
            android_icon="@mipmap/ic_launcher"
            android_label="@string/app_name"
            android_supportsRtl="true"
            android_theme="@style/AppTheme">
            <activity
                android_name=".MainActivity"
                android_label="@string/app_name"
                android_theme="@style/AppTheme.NoActionBar">
                <intent-filter>
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

    More Resources

    Resource Link
    GitHub Browse Browse
    GitHub Download Link Download

     

  4. Adv
  5. Android RecyclerView – Load Images from FileSystem

    Android RecyclerView FileSystem tutorial. How to load images from FileSystem to a recylcerview in android.

    This tutorial explores how to load images from FileSystem in android a Recycerview in android. We show both the image and image name in cards in our recyclerview.

    Tools Used

    This example was written with the following tools:

    • Windows 8
    • AndroidStudio IDE
    • Genymotion Emulator
    • Language : Java

    Source Code

    Lets jump directly to the source code. Source code is well commented.

    Video Tutorial

    • We have a YouTube channel with almost a thousand tutorials, this one below being one of them.

    https://youtu.be/ZEqe5t3X0Ko

    Download

    • You can Download the full Project below. Source code is well commented.

    Download

    How To Run

    1. Download the project above.
    2. You’ll get a zipped file,extract it.
    3. Open the Android Studio.
    4. Now close, already open project.
    5. From the Menu bar click on File >New> Import Project.
    6. Now Choose a Destination Folder, from where you want to import project.
    7. Choose an Android Project.
    8. Now Click on “OK“.
    9. Done, your done importing the project,now edit it.

    More

    YouTube

    • Visit our channel for more examples like these.

    Facebook

     




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )