Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check Android Asset resource?

I want to check, whether a file exists or not in the /assets/ folder. How could I do it? Please help.

like image 692
Mudassir Avatar asked Nov 11 '10 10:11

Mudassir


2 Answers

I added a helper method to one of my application classes. I'm assuming that;

  1. the list of assets doesn't change while the app is running.
  2. the List<String> isn't a memory hog (only 78 assets in my app).
  3. checking exists() on the List is faster than trying to open a File and handle an exception (I haven't actually profiled this).
AssetManager am;
List<String> mapList;

/**
 * Checks if an asset exists.
 *
 * @param assetName
 * @return boolean - true if there is an asset with that name.
 */
public boolean checkIfInAssets(String assetName) {
    if (mapList == null) {
        am = getAssets();
        try {
            mapList = Arrays.asList(am.list(""));
        } catch (IOException e) {
        }
    }
    return mapList.contains(assetName);
}
like image 163
geoffc Avatar answered Oct 16 '22 09:10

geoffc


You could also just try to open the stream, if it fails the file is not there and if it does not fail the file should be there:

/**
 * Check if an asset exists. This will fail if the asset has a size < 1 byte.
 * @param context
 * @param path
 * @return TRUE if the asset exists and FALSE otherwise
 */
public static boolean assetExists(Context context, String path) {
    boolean bAssetOk = false;
    try {
        InputStream stream = context.getAssets().open(ASSET_BASE_PATH + path);
        stream.close();
        bAssetOk = true;
    } catch (FileNotFoundException e) {
        Log.w("IOUtilities", "assetExists failed: "+e.toString());
    } catch (IOException e) {
        Log.w("IOUtilities", "assetExists failed: "+e.toString());
    }
    return bAssetOk;
}
like image 29
Moss Avatar answered Oct 16 '22 07:10

Moss