Android FilePicker GridView Images

Android RSS : ListView Multiple Fields – Download,Parse,Show Headlines
Android RSS : GridView- Downlaod,Parse,Show Headlines With Images and Text
Android RSS : GridView- Download,Parse,Show Headlines With Images and Text

Android FilePicker GridView Images







Introduction

 Look the aim is simple.To load images from our File System and into our GridView.Maybe we can do that via a loop but see we want control.We want to select images we load,not just loop through and load all images,though we have such a tutorial as well.So we shall be using a FilePicker,a material filepicker third party library to help us choose images with a nice material interface.Moreover we can define the total number of images users can choose at a go.

We then display these images in a GridView.

Our images exist in the external storage in the device's filesystem
You can find more details about External Storage here.

Common Questions this example explores

  • Android FilePicker example.
  • Android Pick images From SD Card to GridView.
  • Android Material Filepicker Gridview
  • Retrieving images from external storage.
  • Get image from filesystem to an GridView
  • Android Filesystem example.

Tools Used

This example was written with the following tools:

  • Windows 8
  • AndroidStudio IDE
  • BlueStacks Emulator

 

So the first thing is to add the dependency in our build.gradle app level,as in :

compile 'com.droidninja:filepicker:1.0.0'

 

We shall have something like this,simply overriding our onActivityResult() method in our MainActivity.We have a model class we called spacecraft,we simply then assign it properties depending on what we receive from the files we are loading.  :

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case FilePickerConst.REQUEST_CODE:
                if(resultCode==RESULT_OK && data!=null)
                {
                    filePaths = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_PHOTOS);
                    Spacecraft s;
                    ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
                    try
                    {
                        for (String path:filePaths) {
                            s=new Spacecraft();
                            s.setName(path.substring(path.lastIndexOf("/")+1));
                            s.setUri(Uri.fromFile(new File(path)));
                            spacecrafts.add(s);
                        }
                        gv.setAdapter(new CustomAdapter(this,spacecrafts));
                        Toast.makeText(MainActivity.this, "Total = "+String.valueOf(spacecrafts.size()), Toast.LENGTH_SHORT).show();
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
        }
    
}

 

 

Screenshot

  • Here’s the screenshot of the project.

Images Selector
Images Selector

Images Selected From FileSystem To GridView
Images In GridView

Source Code

Lets have a look at the source code.

Build.GradleActivityMain.xmlContentMain.xmlModel.xmlSpacecraft.javaCustomAdapter.javaMainActivity.javaVideo/Preview”Download”
  • This is our app level build.gradle. It’s located inside the app directory.
  • We sepcify any dependencies required by the project here.
  • Our dependencies can either be SDK-based e.g appcompat and design support libraries or be fetched from third party repository via internet.
  • In this case we fetch Picasso(com.squareup.picasso:picasso) and FilePicker(com.droidninja:filepicker) from external repository.
apply plugin: 'com.android.application'
android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.tutorials.hp.filepickergridview"
        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.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:cardview-v7:24.1.1'
    compile 'com.droidninja:filepicker:1.0.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

 

  • This is the container layout of our mainactivity.
  • It specifies the appbar layout, toolbar and floating action button.
  • It also includes the contentmain.xml layout where we actually add our widgets.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.filepickergridview.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>

 

  • This is where we add our widgets and views for our mainactivity.
  • In this case we have a gridview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    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.filepickergridview.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>

 

  • This layout gets inflated to a single viewitem in our gridview.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    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:paddingLeft="10dp"
                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>

 

  • This is the definition of a spaceraft object.
  • It specifies it’s properties like name and filesystem image uri.
package com.tutorials.hp.filepickergridview;
import android.net.Uri;
/**
 * Created by Oclemy on 8/4/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class Spacecraft {
    String name;
    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;
    }
}

 

  • This is our adapter class. It adapts our data to our views.
  • It inherits from BaseAdapter.
package com.tutorials.hp.filepickergridview;
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;
/**
 * Created by Oclemy on 8/4/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
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;
    }
}

 

  • Here's our mainactivity.
package com.tutorials.hp.filepickergridview;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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.GridView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import droidninja.filepicker.FilePickerBuilder;
import droidninja.filepicker.FilePickerConst;
public class MainActivity extends AppCompatActivity {
    ArrayList<String> filePaths=new ArrayList<String>();
    GridView gv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        gv= (GridView) findViewById(R.id.gv);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                filePaths.clear();
                FilePickerBuilder.getInstance().setMaxCount(5)
                        .setSelectedFiles(filePaths)
                        .setActivityTheme(R.style.AppTheme)
                        .pickPhoto(MainActivity.this);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case FilePickerConst.REQUEST_CODE:
                if(resultCode==RESULT_OK && data!=null)
                {
                    filePaths = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_PHOTOS);
                    Spacecraft s;
                    ArrayList<Spacecraft> spacecrafts=new ArrayList<>();
                    try
                    {
                        for (String path:filePaths) {
                            s=new Spacecraft();
                            s.setName(path.substring(path.lastIndexOf("/")+1));
                            s.setUri(Uri.fromFile(new File(path)));
                            spacecrafts.add(s);
                        }
                        gv.setAdapter(new CustomAdapter(this,spacecrafts));
                        Toast.makeText(MainActivity.this, "Total = "+String.valueOf(spacecrafts.size()), Toast.LENGTH_SHORT).show();
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
        }
    }
}

 

Android Material FilePicker Ep.01 : GridView - Pick Multiple Images, Show

  • Download the Project below:

How To Run

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

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.



Rating :

    Leave a Reply

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

    18 + 8 =

    COMMENTS