Picasso — Advanced Loading

Last week, we've looked at reasons for using Picasso and a simple example request to load an image from an Internet source. But this cannot be the only source for Picasso. Picasso can also load images from the Android resources, files and Uri's. In this blog post, we'll cover all three options.

Picasso Series Overview

Loading from Resources

First up is loading from Android resources. Instead of giving a String pointing to an Internet URL, you give a resource int.

int resourceId = R.mipmap.ic_launcher;

Picasso  
    .with(context)
    .load(resourceId)
    .into(imageViewResource);

If you're confused by the R.mipmap., it's Android's new way of handling icons.

Loading from File

Second up is loading from a file. This can be useful when you let the user select a photo to display an image (similar to a gallery). The parameter is just a File object. In an example, we look

// this file probably does not exist on your device. However, you can use any file path, which points to an image file

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Running.jpg");

Picasso  
    .with(context)
    .load(file)
    .into(imageViewFile);

Loading from Uri

Lastly, you can also load images defined by an Uri. The request is no different from the previous options:

// this could be any Uri. for demonstration purposes we're just creating an Uri pointing to a launcher icon

Uri uri = resourceIdToUri(context, R.mipmap.future_studio_launcher);

Picasso  
    .with(context)
    .load(uri)
    .into(imageViewUri);

The small helper function is a simple conversion from the resourceId to an Uri.

public static final String ANDROID_RESOURCE = "android.resource://";  
public static final String FORWARD_SLASH = "/";

private static Uri resourceIdToUri(Context context, int resourceId) {  
    return Uri.parse(ANDROID_RESOURCE + context.getPackageName() + FORWARD_SLASH + resourceId);
}

However, the Uri does not have to be generated from a resourceId. It can be any Uri.

Outlook

The basic loading principles are done, now we can finally look at more interesting stuff. Next week we'll cover adapter use and Picasso's caching in ListViews and GridViews.

Explore the Library

Find interesting tutorials and solutions for your problems.