DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Make A Gallery-Like Image Grid Using Native Android
Content provided by Couchbase logo

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.

Nic Raboy user avatar by
Nic Raboy
·
Jun. 11, 15 · Interview
Like (0)
Save
Tweet
Share
6.49K Views

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.

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



Comments

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: