Example usage for android.content.res AssetManager open

List of usage examples for android.content.res AssetManager open

Introduction

In this page you can find the example usage for android.content.res AssetManager open.

Prototype

public @NonNull InputStream open(@NonNull String fileName) throws IOException 

Source Link

Document

Open an asset using ACCESS_STREAMING mode.

Usage

From source file:com.clutch.ClutchConf.java

public static JSONObject getConf() {
    if (conf != null) {
        return conf;
    }//  w w  w.j a  va 2 s. c  o m

    String versionName = "";
    try {
        versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "Could not get bundle version");
        e.printStackTrace();
    }

    // First we look for a saved plist file that ClutchSync creates
    File dir = context.getDir("_clutch" + versionName, 0);
    File clutch = null;
    for (File f : dir.listFiles()) {
        if (f.getName().equals("clutch.json")) {
            clutch = f;
            break;
        }
    }

    // If we found it, then parse it and set ourselves, then return the data.
    if (clutch != null) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(clutch));
            StringBuffer sb = new StringBuffer();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
            conf = new JSONObject(sb.toString());
            br.close();
            return conf;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // If we didn't find it in the filesystem, check in the assets
    final AssetManager mgr = context.getAssets();
    String asset = ClutchUtils.findAsset(mgr, "./", "clutch.json");
    if (asset == null) {
        conf = new JSONObject();
        return conf;
    }

    try {
        InputStream fin = mgr.open(asset);
        String data = new Scanner(fin).useDelimiter("\\A").next();
        conf = new JSONObject(data);
        return conf;
    } catch (java.util.NoSuchElementException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    conf = new JSONObject();

    return conf;
}

From source file:com.geomoby.geodeals.DemoService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from   w w w.j  av  a  2 s. c o  m*/
private static void generateNotification(Context context, String message) {
    if (message.length() > 0) {

        // Parse the GeoMoby message using the GeoMessage class
        try {
            Gson gson = new Gson();
            JsonParser parser = new JsonParser();
            JsonArray Jarray = parser.parse(message).getAsJsonArray();
            ArrayList<GeoMessage> alerts = new ArrayList<GeoMessage>();
            for (JsonElement obj : Jarray) {
                GeoMessage gName = gson.fromJson(obj, GeoMessage.class);
                alerts.add(gName);
            }

            // Prepare Notification and pass the GeoMessage to an Extra
            NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            Intent i = new Intent(context, CustomNotification.class);
            i.putParcelableArrayListExtra("GeoMessage", (ArrayList<GeoMessage>) alerts);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Read from the /assets directory
            Resources resources = context.getResources();
            AssetManager assetManager = resources.getAssets();
            try {
                InputStream inputStream = assetManager.open("geomoby.properties");
                Properties properties = new Properties();
                properties.load(inputStream);
                String push_icon = properties.getProperty("push_icon");
                int icon = resources.getIdentifier(push_icon, "drawable", context.getPackageName());
                int not_title = resources.getIdentifier("notification_title", "string",
                        context.getPackageName());
                int not_text = resources.getIdentifier("notification_text", "string", context.getPackageName());
                int not_ticker = resources.getIdentifier("notification_ticker", "string",
                        context.getPackageName());

                // Manage notifications differently according to Android version
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

                    builder.setSmallIcon(icon).setContentTitle(context.getResources().getText(not_title))
                            .setContentText(context.getResources().getText(not_text))
                            .setTicker(context.getResources().getText(not_ticker))
                            .setContentIntent(pendingIntent).setAutoCancel(true);

                    builder.setDefaults(Notification.DEFAULT_ALL); //Vibrate, Sound and Led

                    // Because the ID remains unchanged, the existing notification is updated.
                    notificationManager.notify(notifyID, builder.build());

                } else {
                    Notification notification = new Notification(icon, context.getResources().getText(not_text),
                            System.currentTimeMillis());

                    //Setting Notification Flags
                    notification.defaults |= Notification.DEFAULT_ALL;
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    //Set the Notification Info
                    notification.setLatestEventInfo(context, context.getResources().getText(not_text),
                            context.getResources().getText(not_ticker), pendingIntent);

                    //Send the notification
                    // Because the ID remains unchanged, the existing notification is updated.
                    notificationManager.notify(notifyID, notification);
                }
            } catch (IOException e) {
                System.err.println("Failed to open geomoby property file");
                e.printStackTrace();
            }
        } catch (JsonParseException e) {
            Log.i(TAG, "This is not a GeoMoby notification");
            throw new RuntimeException(e);
        }
    }
}

From source file:org.openmrs.mobile.utilities.FormsLoaderUtil.java

/**
 * Loads pre-defined forms, generated with OpenMRS XForm module,
 * from assets and saves them in database
 * @param manager//w w  w. ja  v a 2s  . c o m
 */
public static void loadDefaultForms(AssetManager manager) {
    InputStream inputStream = null;
    for (String formName : DEFAULT_FORMS) {
        String formNameWithExtension = formName + FormsLoaderUtil.XML_SUFFIX;
        if (OpenMRS.getInstance().getDefaultFormLoadID(formName).isEmpty()) {
            try {
                inputStream = manager.open(FormsLoaderUtil.ASSET_DIR + formNameWithExtension);
            } catch (IOException e) {
                OpenMRS.getInstance().getOpenMRSLogger().d(e.toString());
                OpenMRS.getInstance().getOpenMRSLogger().d("Failed to load form : " + formName);
            }
            OpenMRS.getInstance().setDefaultFormLoadID(formName,
                    FormsLoaderUtil.copyFormFromAssets(formNameWithExtension, inputStream));
        }
    }

}

From source file:run.ace.Utils.java

public static Bitmap getBitmapAsset(android.content.Context context, String url) {
    InputStream inputStream = null;
    Bitmap b = null;//  www .  j a v a2 s  .  co  m

    try {
        if (url.contains("{platform}")) {
            url = url.replace("{platform}", "android");
        }

        AssetManager assetManager = context.getAssets();
        inputStream = assetManager.open(url);
    } catch (IOException ex) {
    }

    if (inputStream != null) {
        b = BitmapFactory.decodeStream(inputStream);
        try {
            inputStream.close();
        } catch (IOException ex) {
        }
    }
    return b;
}

From source file:Main.java

private static void copyAssetFolder(AssetManager am, String src, String dest) throws IOException {

    Log.i("Copy ", src);
    InputStream srcIS = null;// w  w  w  .  ja  va 2  s.  c  o  m
    File destfh;

    // this is the only way we can tell if this is a file or a
    // folder - we have to open the asset, and if the open fails,
    // it's a folder...
    boolean isDir = false;
    try {
        srcIS = am.open(src);
    } catch (FileNotFoundException e) {
        isDir = true;
    }

    // either way, we'll use the dest as a File
    destfh = new File(dest);

    // and now, depending on ..
    if (isDir) {

        // If the directory doesn't yet exist, create it
        if (!destfh.exists()) {
            destfh.mkdir();
        }

        // list the assets in the directory...
        String assets[] = am.list(src);

        // and copy them all using same.
        for (String asset : assets) {
            copyAssetFolder(am, src + "/" + asset, dest + "/" + asset);
        }

    } else {
        int count, buffer_len = 2048;
        byte[] data = new byte[buffer_len];

        // copy the file from the assets subsystem to the filesystem
        FileOutputStream destOS = new FileOutputStream(destfh);

        //copy the file content in bytes
        while ((count = srcIS.read(data, 0, buffer_len)) != -1) {
            destOS.write(data, 0, count);
        }

        // and close the two files
        srcIS.close();
        destOS.close();
    }
}

From source file:crow.util.Util.java

/**
 * Assists ?//from   w  ww. j  a v a 2  s .c o  m
 */
public static String getAssistFileAsString(Context context, String assistFile) throws IOException {
    String result = null;
    AssetManager assetManager = context.getAssets();
    result = inputStreamToString(assetManager.open(assistFile));
    return result;
}

From source file:com.simas.vc.helpers.Utils.java

/**
 * Will use {@code destinationPath/assetFileName} as the output file
 * @param assetName          Asset name//from   w w w.java 2 s  . c om
 * @param destinationDir     Absolute path to the output directory
 */
public static void copyAsset(String assetName, String destinationDir) throws IOException {
    AssetManager assetManager = VC.getAppContext().getAssets();
    InputStream is = assetManager.open(assetName);
    File destinationFile = new File(destinationDir + File.separator + assetName);
    if (!destinationFile.exists()) {
        // If destinationDir creation failed or it already exists
        // AND
        // Failed to create a new file or it already exists =>
        // Throw because previous condition said it doesn't exist
        if (!new File(destinationDir).mkdirs() && !destinationFile.createNewFile()) {
            throw new IOException("The destination file doesn't exist and couldn't be" + "created! "
                    + destinationFile.getPath());
        }
    }
    copyBytes(is, destinationFile);
}

From source file:Main.java

public final static void copyAsset(String tag, AssetManager assets, String assetName, File target) {
    if (target.exists()) {
        Log.d(tag, String.format("asset %s already installed at %s", assetName, target));
    } else {/* ww  w. j av  a2 s.c o m*/
        Log.d(tag, String.format("copying asset %s to %s", assetName, target));
        InputStream is = null;
        OutputStream os = null;
        try {
            is = assets.open(assetName);
            os = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            int count;
            while ((count = is.read(buffer)) != -1)
                os.write(buffer, 0, count);
        } catch (IOException e) {
            Log.e(tag, "copy", e);
        } finally {
            closeQuietly(is);
            closeQuietly(os);
        }
    }
}

From source file:cn.mdict.utils.IOUtil.java

public static boolean loadStringFromAsset(AssetManager assets, String filename, StringBuffer str,
        boolean overwriteByFile) {
    try {//w ww.ja  v a 2s.  com
        if (overwriteByFile) {
            if (loadStringFromFile(MdxEngine.getDocDir() + filename, str))
                return true;
        }
        return loadStringFromStream(assets.open(filename), "UTF8", str);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:com.group7.dragonwars.engine.MapReader.java

private static List<String> readFile(final String filename, final Activity activity) {
    AssetManager am = activity.getAssets();
    List<String> text = new ArrayList<String>();

    try {/*from   ww  w .ja  v  a2s  .  co m*/
        BufferedReader in = new BufferedReader(new InputStreamReader(am.open(filename)));
        String line;

        while ((line = in.readLine()) != null) {
            text.add(line);
        }

        in.close();
    } catch (FileNotFoundException fnf) {
        System.err.println("Couldn't find " + fnf.getMessage());
        System.exit(1);
    } catch (IOException ioe) {
        System.err.println("Couldn't read " + ioe.getMessage());
        System.exit(1);
    }

    return text;
}