Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Make A Gallery-Like Image Grid Using Native Android

DZone's Guide to

Make A Gallery-Like Image Grid Using Native Android

In this tutorial we’ll see how to make use of the Android GridView with an image adapter to display remote images from the internet.

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

Previously I had written an article regarding how to make a gallery-like image grid using Ionic Framework, but what if we wanted to accomplish the same using the native Android SDK?

In this tutorial we’ll see how to make use of the Android GridView with an image adapter to display remote images from the internet.

Like with all my tutorials, we’ll be using only a terminal and text editor.  So no IDE such as Android Studio or Eclipse.  From your command prompt or terminal, run the following:

android create project --activity MainActivity --package com.nraboy.imagegrid --path ./ImageGrid --target android-19 --gradle --gradle 0.11.+

You’ll notice in the above command we are creating our project with the intention of using Gradle instead of Apache Ant.

Let’s start with the simple stuff first.  In your newly created project, open the src/res/AndroidManifest.xml file and add the internet permission like so:

<uses-permission android:name="android.permission.INTERNET" />

We are doing this because we will be displaying images directly from the internet.

Native Android Image Grid

Above is a picture of what we’re after for this example.

When it comes to designing this application, let’s start with the Android view XML code.  Open your project’ssrc/res/layout/main.xml file and add replace it with the following code:

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="115dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />

We are creating an Android GridView where each column of the grid will be 115dp in size and have 5dp x 5dp spacing.

GridView in Android is populated using some form of adapter.  In this case we’ll be creating our own custom adapter.  Create a src/main/java/com/nraboy/imagegrid/ImageAdapter.java file and add the following code:

package com.nraboy.imagegrid;

import android.app.*;
import android.os.*;
import android.widget.*;
import java.util.*;
import android.graphics.*;
import android.view.*;
import android.content.*;

public class ImageAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Bitmap> bitmapList;

    public ImageAdapter(Context context, ArrayList<Bitmap> bitmapList) {
        this.context = context;
        this.bitmapList = bitmapList;
    }

    public int getCount() {
        return this.bitmapList.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(this.context);
            imageView.setLayoutParams(new GridView.LayoutParams(115, 115));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageBitmap(this.bitmapList.get(position));
        return imageView;
    }

}

In the above code we are essentially taking an ArrayList of Bitmap and assigning the content at any given index to a particular cell in the grid.  We are lucky enough to have the getView function determine the current view and position.  The view being the cell.

This brings us to the MainActivity class we created when building our project from the command line.  We’re going to capture the grid from our XML and populate it with images of our choice.  Open your src/main/java/com/nraboy/imagegrid/MainActivity.java file and add the following code:

package com.nraboy.imagegrid;

import android.app.Activity;
import android.os.Bundle;
import android.graphics.*;
import java.util.*;
import java.net.*;
import android.widget.*;

public class MainActivity extends Activity {

    private GridView imageGrid;
    private ArrayList<Bitmap> bitmapList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.imageGrid = (GridView) findViewById(R.id.gridview);
        this.bitmapList = new ArrayList<Bitmap>();

        this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));

    }

}

Wait a second!  How are we going to get our images in there?  We are assigning our custom adapter to the grid, but there are no images in the ArrayList.  In this particular example we’re going to be loading our images directly from the internet.  You can choose to load bitmap images however you wish.

private Bitmap urlImageToBitmap(String imageUrl) throws Exception {
    Bitmap result = null;
    URL url = new URL(imageUrl);
    if(url != null) {
        result = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    }
    return result;
}

The above function will take a remote image from URL and load it as a bitmap.  So all together in our MainActivity class, we have the following:

package com.nraboy.imagegrid;

import android.app.Activity;
import android.os.Bundle;
import android.graphics.*;
import java.util.*;
import java.net.*;
import android.widget.*;

public class MainActivity extends Activity {

    private GridView imageGrid;
    private ArrayList<Bitmap> bitmapList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        this.imageGrid = (GridView) findViewById(R.id.gridview);
        this.bitmapList = new ArrayList<Bitmap>();

        try {
            for(int i = 0; i < 10; i++) {
                this.bitmapList.add(urlImageToBitmap("http://placehold.it/150x150"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.imageGrid.setAdapter(new ImageAdapter(this, this.bitmapList));

    }

    private Bitmap urlImageToBitmap(String imageUrl) throws Exception {
        Bitmap result = null;
        URL url = new URL(imageUrl);
        if(url != null) {
            result = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        }
        return result;
    }

}

I’ve chosen just to load ten generic placeholder images in the above code.

To build this, from your terminal or command prompt, run the following Gradle command:

./gradlew assemble

You should have a ImageGrid-debug.apk file generated in the build/output/apk directory.

Conclusion

It is not too difficult to create a grid of images using native Android.  If you’ve been keeping up with my tutorials, you’ve now seen the native Android method, as well as the hybrid method with Ionic Framework.  We populated our grid of images using remote images from the internet loaded into bitmap form.


Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
java ,mobile ,android ,apache ant ,gradle

Published at DZone with permission of Nic Raboy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}