Search code examples
javaandroidmysqlthumbnailsair-native-extension

Android thumbnail list


For my flash app i needed to create a "native extension", which is a native android Java call. This extension builds a string which consist of all image files and their corresponding thumbnails and returns it to Flash.

I'm not a Java programmer and this is my first attempt on writing android code. So after 2 days of digging I came up with this:

public String getThumbPaths(Uri uri, ThumbContext ctx) {
    String out = "";
    Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnails(ctx
            .getActivity().getContentResolver(), uri,
            MediaStore.Images.Thumbnails.MINI_KIND, null);


    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

        String imageId = cursor.getString(cursor
                .getColumnIndex(Thumbnails.IMAGE_ID));

        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor images = ctx.getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                filePathColumn, MediaStore.Images.Media._ID + "=?",
                new String[] { imageId }, null);

        String filePath = "";

        if (images != null && images.moveToFirst()) {
            filePath = images.getString(images.getColumnIndex(filePathColumn[0]));
        }

        out += cursor.getString(1) + ";" + filePath+";";

    }

    return out;
}

and the call

ThumbContext ctx = (ThumbContext) context;
Uri uri = MediaStore.Images.Thumbnails.getContentUri("external"); // content://media/external/images/thumbnails
String paths = getThumbPaths(uri, ctx);

Everything works well, except for the speed. I don't know if this happens because of Flash-Java-Flash calls or the piece of code above, which i can't check because the compilation happens inside the Flash.

So my question is: can i speed up this code? Maybe do this without second cursor inside the "for" loop?


Solution

  • There are several little bits of optimization you can do.

    1. cursor.getColumnIndex(Thumbnails.IMAGE_ID) will return the same value for every iteration through the cursor. Assign it to a variable outside the loop.
    2. String[] filePathColumn is assigned the same value on every iteration (and creates a new object on every iteration as well). Move it outside the loop.
    3. For the inner Cursor, MediaStore.Images.Media._ID + "=?" always has the same value. Outside the loop :)
    4. Instead of creating out as a String and appending to it, consider using java.lang.StringBuilder instead.