1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.wearable.recipeassistant; 18 19 import android.content.Context; 20 import android.graphics.Bitmap; 21 import android.graphics.BitmapFactory; 22 import android.util.Log; 23 24 import org.json.JSONException; 25 import org.json.JSONObject; 26 27 import java.io.IOException; 28 import java.io.InputStream; 29 30 final class AssetUtils { 31 private static final String TAG = "RecipeAssistant"; 32 loadAsset(Context context, String asset)33 public static byte[] loadAsset(Context context, String asset) { 34 byte[] buffer = null; 35 try { 36 InputStream is = context.getAssets().open(asset); 37 int size = is.available(); 38 buffer = new byte[size]; 39 is.read(buffer); 40 is.close(); 41 } catch (IOException e) { 42 Log.e(TAG, "Failed to load asset " + asset + ": " + e); 43 } 44 return buffer; 45 } 46 loadJSONAsset(Context context, String asset)47 public static JSONObject loadJSONAsset(Context context, String asset) { 48 String jsonString = new String(loadAsset(context, asset)); 49 JSONObject jsonObject = null; 50 try { 51 jsonObject = new JSONObject(jsonString); 52 } catch (JSONException e) { 53 Log.e(TAG, "Failed to parse JSON asset " + asset + ": " + e); 54 } 55 return jsonObject; 56 } 57 loadBitmapAsset(Context context, String asset)58 public static Bitmap loadBitmapAsset(Context context, String asset) { 59 InputStream is = null; 60 Bitmap bitmap = null; 61 try { 62 is = context.getAssets().open(asset); 63 if (is != null) { 64 bitmap = BitmapFactory.decodeStream(is); 65 } 66 } catch (IOException e) { 67 Log.e(TAG, e.toString()); 68 } finally { 69 if (is != null) { 70 try { 71 is.close(); 72 } catch (IOException e) { 73 Log.e(TAG, "Cannot close InputStream: ", e); 74 } 75 } 76 } 77 return bitmap; 78 } 79 } 80