Example usage for android.content.res Resources getAssets

List of usage examples for android.content.res Resources getAssets

Introduction

In this page you can find the example usage for android.content.res Resources getAssets.

Prototype

public final AssetManager getAssets() 

Source Link

Document

Retrieve underlying AssetManager storage for these resources.

Usage

From source file:Main.java

public static Bitmap getBitmapForDensity(Resources res, int displayDpi, int resId) {
    try {//  w  w w.j  a va 2s.  c om
        TypedValue value = new TypedValue();
        res.getValueForDensity(resId, displayDpi, value, true);
        AssetFileDescriptor fd = res.getAssets().openNonAssetFd(value.assetCookie, value.string.toString());
        Options opt = new Options();
        opt.inTargetDensity = displayDpi;
        Bitmap bitmap = BitmapFactory.decodeResourceStream(res, value, fd.createInputStream(), null, opt);
        bitmap.setDensity(res.getDisplayMetrics().densityDpi);
        fd.close();
        return bitmap;
    } catch (Exception e) {
        return BitmapFactory.decodeResource(res, resId);
    }
}

From source file:com.bellman.bible.service.common.FileManager.java

public static Properties readPropertiesFile(String folder, String filename) {
    Properties returnProperties = new Properties();

    Resources resources = CurrentActivityHolder.getInstance().getApplication().getResources();
    AssetManager assetManager = resources.getAssets();
    if (!filename.endsWith(DOT_PROPERTIES)) {
        filename = filename + DOT_PROPERTIES;
    }/*ww  w  . ja  va2  s  . c  o m*/
    if (StringUtils.isNotEmpty(folder)) {
        filename = folder + File.separator + filename;
    }

    // Read from the /assets directory
    InputStream inputStream = null;
    try {
        // check to see if a user has created his own reading plan with this name
        inputStream = assetManager.open(filename);

        returnProperties.load(inputStream);
        log.debug("The properties are now loaded from: " + filename);
    } catch (IOException e) {
        System.err.println("Failed to open property file:" + filename);
        e.printStackTrace();
    } finally {
        IOUtil.close(inputStream);
    }
    return returnProperties;
}

From source file:com.jarklee.materialdatetimepicker.Utils.java

public static String getStringFromLocale(@NonNull Context context, @StringRes int strRes, Locale locale) {
    if (locale == null) {
        return context.getString(strRes);
    }//from   w ww.j  av a 2  s  . co  m
    Resources standardResources = context.getResources();
    AssetManager assets = standardResources.getAssets();
    DisplayMetrics metrics = standardResources.getDisplayMetrics();
    Configuration config = new Configuration(standardResources.getConfiguration());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLocale(locale);
    } else {
        config.locale = locale;
    }
    Resources defaultResources = new Resources(assets, metrics, config);
    try {
        return defaultResources.getString(strRes);
    } catch (Exception e) {
        return context.getString(strRes);
    }
}

From source file:Main.java

private static String loadFromAssets(Resources resources, String fileName) {
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();

    try {//w  w  w.jav  a2s  .c  o m
        reader = new BufferedReader(new InputStreamReader(resources.getAssets().open(fileName), "UTF-8"));

        // do reading, usually loop until end of file reading
        String mLine = reader.readLine();
        while (mLine != null) {
            sb.append(mLine).append('\n');
            mLine = reader.readLine();
        }
    } catch (IOException e) {
        //log the exception
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                //log the exception
            }
        }
    }

    return sb.toString();
}

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

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from  www . j  a  va  2  s .co 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:com.mikecorrigan.trainscorekeeper.ActivityNewGame.java

private void addContent() {
    Log.vc(VERBOSE, TAG, "addContent");

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);

    Resources res = getResources();
    AssetManager am = res.getAssets();
    String files[];//  ww  w .  j  av a 2s  .c o  m
    try {
        files = am.list(ASSETS_BASE);
        if (files == null || files.length == 0) {
            Log.e(TAG, "addContent: empty asset list");
            return;
        }

        for (final String file : files) {
            final String path = ASSETS_BASE + File.separator + file;

            JSONObject jsonRoot = JsonUtils.readFromAssets(this /* context */, path);
            if (jsonRoot == null) {
                Log.e(file, "addContent: failed to read read asset");
                continue;
            }

            final String name = jsonRoot.optString(JsonSpec.ROOT_NAME);
            if (TextUtils.isEmpty(name)) {
                Log.e(file, "addContent: failed to read asset name");
                continue;
            }

            final String description = jsonRoot.optString(JsonSpec.ROOT_DESCRIPTION, name);

            TextView textView = new TextView(this /* context */);
            textView.setText(name);
            linearLayout.addView(textView);

            Button button = new Button(this /* context */);
            button.setText(description);
            button.setOnClickListener(new OnRulesClickListener(path));
            linearLayout.addView(button);
        }
    } catch (IOException e) {
        Log.th(TAG, e, "addContent: asset list failed");
    }
}

From source file:android.content.res.VectorResources.java

public VectorResources(Context context, Resources res) {
    super(res.getAssets(), res.getDisplayMetrics(), res.getConfiguration());
    mContext = context;/*from ww  w.  j  a v  a 2 s . c  o  m*/
    mBase = res;
}

From source file:com.thedamfr.facebook_dashclock_ext.ExampleExtension.java

@Override
protected void onUpdateData(int reason) {
    Session fbSession = Session.getActiveSession();
    if (fbSession == null) {
        Resources resources = this.getResources();
        AssetManager assetManager = resources.getAssets();
        Properties properties = new Properties();
        // Read from the /assets directory
        try {//from w  w  w.  java2  s . c  om
            InputStream inputStream = assetManager.open("facebook.properties");
            properties.load(inputStream);
            System.out.println("The properties are now loaded");
            //System.out.println("properties: " + properties);
        } catch (IOException e) {
            System.err.println("Failed to open facebook property file");
            e.printStackTrace();
        }

        Session session = new Session.Builder(this).setApplicationId(properties.getProperty("app_id", ""))
                .build();
        Session.setActiveSession(session);
        fbSession = session;
    }
    if (fbSession != null && !fbSession.isOpened()) {
        Intent intent = new Intent(this, RefreshSessionActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    if (fbSession.isOpened()) {
        Request notificationsRequest = Request.newGraphPathRequest(fbSession, "me/notifications",
                new Request.Callback() {

                    @Override
                    public void onCompleted(Response response) {
                        GraphObject object = response.getGraphObject();
                        if (object != null) {
                            JSONArray notifications = (JSONArray) object.getProperty("data");
                            if (notifications.length() >= 1) {
                                // Publish the extension data update.
                                String title = null;
                                String link = null;
                                try {
                                    title = ((JSONObject) notifications.get(0)).getString("title");
                                    link = ((JSONObject) notifications.get(0)).getString("link");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    title = "Can't read title";
                                }
                                publishUpdate(new ExtensionData().visible(true).icon(R.drawable.icon)
                                        .status("New Content")
                                        .expandedTitle(notifications.length() + "  notifications")
                                        .expandedBody(title)
                                        .clickIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(link))));

                            } else {
                                publishUpdate(new ExtensionData().visible(false).status("No Content"));
                            }
                        } else {
                            publishUpdate(new ExtensionData().visible(false).status("No Content"));
                        }

                    }
                });

        notificationsRequest.executeAsync();
    }

}

From source file:com.bluekai.sampleapp.BlueKaiTab.java

@Override
protected void onResume() {
    super.onResume();
    database = DataSource.getInstance(context);
    DevSettings devSettings = database.getDevSettings();
    if (devSettings == null) {
        try {/*  w ww.ja  v a 2 s  . c o  m*/
            Resources resources = this.getResources();
            AssetManager assetManager = resources.getAssets();
            InputStream inputStream = assetManager.open("settings.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            useHttps = Boolean.parseBoolean(properties.getProperty("useHttps"));
            devMode = Boolean.parseBoolean(properties.getProperty("devmode"));
            siteId = properties.getProperty("siteid");
        } catch (IOException e) {
            Log.e("BlueKaiSampleApp", "Error loading properties. Default values will be loaded from SDK", e);
        }
    } else {
        siteId = devSettings.getBkurl();
        devMode = devSettings.isDevMode();
        useHttps = devSettings.isHttpsEnabled();
    }
    Log.d("BlueKaiSampleApp", "On Resume --> DevMode ---> " + devMode + " -- Site ID --> " + siteId
            + " -- Use Https --> " + useHttps);
    bk = BlueKai.getInstance(this, this, devMode, useHttps, siteId, appVersion, this, new Handler());
    bk.resume();
}

From source file:org.mobiledeeplinking.android.MobileDeepLinking.java

private String readConfigFile() throws IOException {
    Resources resources = this.getApplicationContext().getResources();
    AssetManager assetManager = resources.getAssets();

    InputStream inputStream = assetManager.open("MobileDeepLinkingConfig.json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line;/*from  w  ww  . jav a  2  s  .c o m*/
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    return sb.toString();
}