Android Simple FileSystem Examples

Android Filesystem

In this tutorial we will see how to load images from the file system and into imageview or different adapterviews like listview, gridview and recyclerview.

Example 1: Android ImageView – Image From ExternalStorage

In android there are various storage options for users to persist application data. Normally android apps create and work with app data. Obviously critical data can be persisted in sqlite database or fetched via web services. However, temporary data can just be stored in the filesystem of the device. Android devices come with external storage that can be used to save and retrieve files.

Be aware that external storage can either be removable storage such as SD card or internal non-removable storage. Usually external storage is always a shared storage. This means the data there can be edited by the user or other applications. Suppose a user removes the external storage, it becomes unavailable to your app. It can also be unavailable when mounted to a computer via, say a USB cable.

This tutorial explores how to retrieve image file from the external storage of the device to an imageview. It’s a beginner tutorial meant to show us how to retrieve an external image from the filesystem and use it in our android application. You can find more details about Exernal Storage here.

Common Questions this example explores

  • Android ExternalStorage example.
  • Android SD Card Example.
  • Fetch image from sd card to imageview.
  • Retrieving images from external storage.
  • Get image from filesystem to an imageview
  • Android Filesystem example.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • BlueStacks Emulator

Source Code

Lets jump directly to the source code.

AndroidManifest.xml

  • Given that we are reading an image from external storage, we need permission to read external storage. So add the permission as we have done below.
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="com.tutorials.hp.imageviewfilesystem">

    <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>

Build.Gradle

  • Normally in android projects, there are two build.gradle files. One is the app level build.gradle, the other is project level build.gradle. The app level belongs inside the app folder and its where we normally add our dependencies and specify the compile and target sdks.
  • We need Picasso ImageLoader to load our images from File URI.So add its dependency.
  • Also Add dependencies for AppCompat and Design support libraries.
  • Our MainActivity shall derive from AppCompatActivity while we shall also use Floating action button from design support libraries.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.tutorials.hp.imageviewfilesystem"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

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

MainActivity.java

  • Launcher activity.
  • ActivityMain.xml inflated as the contentview for this activity.
  • Reference our imageview where our image shall be displayed.
package com.tutorials.hp.imageviewfilesystem;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    TextView nameTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        img= (ImageView) findViewById(R.id.img);
       nameTxt= (TextView) findViewById(R.id.nameTxt);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                Uri file=Uri.fromFile(new File(downloadsFolder,"person.png"));

                if(file.toString() != null && file.toString().length()>0)
                {
                    Picasso.with(MainActivity.this).load(file).placeholder(R.drawable.placeholder).into(img);
                    nameTxt.setText(file.toString());
                }else
                {
                    Toast.makeText(MainActivity.this, "Empty URI", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

}

ActivityMain.xml

  • To contain our ContentMain.xml.
<?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.imageviewfilesystem.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>

ContentMain.xml

  • To hold our imageview where the image shall be displayed.
<?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.imageviewfilesystem.MainActivity"
    tools_showIn="@layout/activity_main">

    <TextView
        android_id="@+id/nameTxt"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Image Path" />
    <ImageView
        android_id="@+id/img"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content" />
</RelativeLayout>

Video/Preview

https://www.youtube.com/watch?v=emCUrX0bSdk

Download

Examle 2: 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 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>

2. 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;
    }
}

3. 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;
    }
}

4. 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

Example 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 Project

Create an android project.

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.

Example 3: 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. Source code is well commented.

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.

BEFORE YOU GO

YOU'VE BEEN SELECTED FOR A GIFT

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Related Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code