Example usage for android.content Context getAssets

List of usage examples for android.content Context getAssets

Introduction

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

Prototype

public abstract AssetManager getAssets();

Source Link

Document

Returns an AssetManager instance for the application's package.

Usage

From source file:com.hichinaschool.flashcards.libanki.Utils.java

/** Returns a list of files for the installed custom fonts. */
public static List<AnkiFont> getCustomFonts(Context context) {
    String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory();
    String fontsPath = deckPath + "/fonts/";
    File fontsDir = new File(fontsPath);
    int fontsCount = 0;
    File[] fontsList = null;//w w w. ja v a  2 s  . co m
    if (fontsDir.exists() && fontsDir.isDirectory()) {
        fontsCount = fontsDir.listFiles().length;
        fontsList = fontsDir.listFiles();
    }
    String[] ankiDroidFonts = null;
    try {
        ankiDroidFonts = context.getAssets().list("fonts");
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e);
    }
    List<AnkiFont> fonts = new ArrayList<AnkiFont>();
    for (int i = 0; i < fontsCount; i++) {
        String filePath = fontsList[i].getAbsolutePath();
        String filePathExtension = getFileExtension(filePath);
        for (String fontExtension : FONT_FILE_EXTENSIONS) {
            // Go through the list of allowed extensios.
            if (filePathExtension.equalsIgnoreCase(fontExtension)) {
                // This looks like a font file.
                AnkiFont font = AnkiFont.createAnkiFont(context, filePath, false);
                if (font != null) {
                    fonts.add(font);
                }
                break; // No need to look for other file extensions.
            }
        }
    }
    for (int i = 0; i < ankiDroidFonts.length; i++) {
        // Assume all files in the assets directory are actually fonts.
        AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true);
        if (font != null) {
            fonts.add(font);
        }
    }

    return fonts;
}

From source file:com.google.fpl.liquidfunpaint.ParticleRenderer.java

public void onSurfaceCreated(Context context) {
    // Create the render surfaces
    for (int i = 0; i < mRenderSurface.length; i++) {
        mRenderSurface[i] = new RenderSurface(FB_SIZE, FB_SIZE);
        mRenderSurface[i].setClearColor(Color.argb(0, 255, 255, 255));
    }/*from  ww  w  .  j a va  2s.co m*/

    // Create the blur renderer
    mBlurRenderer = new BlurRenderer();

    // Read in our specific json file
    String materialFile = FileHelper.loadAsset(context.getAssets(), JSON_FILE);
    try {
        JSONObject json = new JSONObject(materialFile);

        // Water particle material. We are utilizing the position and color
        // buffers returned from LiquidFun directly.
        mWaterParticleMaterial = new WaterParticleMaterial(context,
                json.getJSONObject("waterParticlePointSprite"));

        // Initialize attributes specific to this material
        mWaterParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0);
        mWaterParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0);
        mWaterParticleMaterial.addAttribute("aWeight", 1, Material.AttrComponentType.FLOAT, 1, false, 0);
        mWaterParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA);

        // Non-water particle material. We are utilizing the position and
        // color buffers returned from LiquidFun directly.
        mParticleMaterial = new ParticleMaterial(context, json.getJSONObject("otherParticlePointSprite"));

        // Initialize attributes specific to this material
        mParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0);
        mParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0);
        mParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA);

        // Scrolling texture when we copy water particles from FBO to screen
        mWaterScreenRenderer = new ScreenRenderer(context, json.getJSONObject("waterParticleToScreen"),
                mRenderSurface[0].getTexture());

        // Scrolling texture when we copy water particles from FBO to screen
        mScreenRenderer = new ScreenRenderer(context, json.getJSONObject("otherParticleToScreen"),
                mRenderSurface[1].getTexture());

        // Texture for paper
        JSONObject materialData = json.getJSONObject(PAPER_MATERIAL_NAME);
        String textureName = materialData.getString(DIFFUSE_TEXTURE_NAME);
        mPaperTexture = new Texture(context, textureName);
    } catch (JSONException ex) {
        Log.e(TAG, "Cannot parse" + JSON_FILE + "\n" + ex.getMessage());
    }
}

From source file:com.appsimobile.appsii.timezonepicker.TimeZoneData.java

private HashSet<String> loadTzsInZoneTab(Context context) {
    HashSet<String> processedTimeZones = new HashSet<>();
    AssetManager am = context.getAssets();
    InputStream is = null;//  w ww.  j  a v  a  2 s. c  o  m

    /*
     * The 'backward' file contain mappings between new and old time zone
     * ids. We will explicitly ignore the old ones.
     */
    try {
        is = am.open("backward");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = reader.readLine()) != null) {
            // Skip comment lines
            if (!line.startsWith("#") && line.length() > 0) {
                // 0: "Link"
                // 1: New tz id
                // Last: Old tz id
                String[] fields = line.split("\t+");
                String newTzId = fields[1];
                String oldTzId = fields[fields.length - 1];

                final TimeZone tz = TimeZone.getTimeZone(newTzId);
                if (tz == null) {
                    Log.e(TAG, "Timezone not found: " + newTzId);
                    continue;
                }

                processedTimeZones.add(oldTzId);

                if (DEBUG) {
                    Log.e(TAG, "# Dropping identical time zone from backward: " + oldTzId);
                }

                // Remember the cooler/newer time zone id
                if (mDefaultTimeZoneId != null && mDefaultTimeZoneId.equals(oldTzId)) {
                    mAlternateDefaultTimeZoneId = newTzId;
                }
            }
        }
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read 'backward' file.");
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }

    /*
     * zone.tab contains a list of time zones and country code. They are
     * "sorted first by country, then an order within the country that (1)
     * makes some geographical sense, and (2) puts the most populous zones
     * first, where that does not contradict (1)."
     */
    try {
        String lang = Locale.getDefault().getLanguage();
        is = am.open("zone.tab");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.startsWith("#")) { // Skip comment lines
                // 0: country code
                // 1: coordinates
                // 2: time zone id
                // 3: comments
                final String[] fields = line.split("\t");
                final String timeZoneId = fields[2];
                final String countryCode = fields[0];
                final TimeZone tz = TimeZone.getTimeZone(timeZoneId);
                if (tz == null) {
                    Log.e(TAG, "Timezone not found: " + timeZoneId);
                    continue;
                }

                /*
                 * Dropping non-GMT tzs without a country code. They are not
                 * really needed and they are dups but missing proper
                 * country codes. e.g. WET CET MST7MDT PST8PDT Asia/Khandyga
                 * Asia/Ust-Nera EST
                 */
                if (countryCode == null && !timeZoneId.startsWith("Etc/GMT")) {
                    processedTimeZones.add(timeZoneId);
                    continue;
                }

                // Remember the mapping between the country code and display
                // name
                String country = mCountryCodeToNameMap.get(countryCode);
                if (country == null) {
                    country = getCountryNames(lang, countryCode);
                    mCountryCodeToNameMap.put(countryCode, country);
                }

                // TODO Don't like this here but need to get the country of
                // the default tz.

                // Find the country of the default tz
                if (mDefaultTimeZoneId != null && mDefaultTimeZoneCountry == null
                        && timeZoneId.equals(mAlternateDefaultTimeZoneId)) {
                    mDefaultTimeZoneCountry = country;
                    TimeZone defaultTz = TimeZone.getTimeZone(mDefaultTimeZoneId);
                    if (defaultTz != null) {
                        mDefaultTimeZoneInfo = new TimeZoneInfo(defaultTz, country);

                        int tzToOverride = getIdenticalTimeZoneInTheCountry(mDefaultTimeZoneInfo);
                        if (tzToOverride == -1) {
                            if (DEBUG) {
                                Log.e(TAG, "Adding default time zone: " + mDefaultTimeZoneInfo.toString());
                            }
                            mTimeZones.add(mDefaultTimeZoneInfo);
                        } else {
                            mTimeZones.add(tzToOverride, mDefaultTimeZoneInfo);
                            if (DEBUG) {
                                TimeZoneInfo tzInfoToOverride = mTimeZones.get(tzToOverride);
                                String tzIdToOverride = tzInfoToOverride.mTzId;
                                Log.e(TAG, "Replaced by default tz: " + tzInfoToOverride.toString());
                                Log.e(TAG, "Adding default time zone: " + mDefaultTimeZoneInfo.toString());
                            }
                        }
                    }
                }

                // Add to the list of time zones if the time zone is unique
                // in the given country.
                TimeZoneInfo timeZoneInfo = new TimeZoneInfo(tz, country);
                int identicalTzIdx = getIdenticalTimeZoneInTheCountry(timeZoneInfo);
                if (identicalTzIdx == -1) {
                    if (DEBUG) {
                        Log.e(TAG, "# Adding time zone: " + timeZoneId + " ## " + tz.getDisplayName());
                    }
                    mTimeZones.add(timeZoneInfo);
                } else {
                    if (DEBUG) {
                        Log.e(TAG,
                                "# Dropping identical time zone: " + timeZoneId + " ## " + tz.getDisplayName());
                    }
                }
                processedTimeZones.add(timeZoneId);
            }
        }

    } catch (IOException ex) {
        Log.e(TAG, "Failed to read 'zone.tab'.");
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ignored) {
        }
    }

    return processedTimeZones;
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * Typeface/*  ww w .ja  va 2  s.  c om*/
 * @param customFont
 * @return
 */
public static Typeface getTypeface(Context context, String customFont) {
    Typeface tf = fontCache.get(customFont);
    if (tf == null) {
        try {
            tf = Typeface.createFromAsset(context.getAssets(), customFont);
        } catch (Exception e) {
            return null;
        }
        fontCache.put(customFont, tf);
    }
    return tf;
}

From source file:ca.bitwit.postcard.PostcardAdaptor.java

/**
 * Cordova Plugin Overrides//from   ww  w .jav  a 2 s.  c om
 */

public PostcardAdaptor(Activity activity, WebView webView) {
    Log.d("PostcardApplication", "Initialized");
    NetworksManager.INSTANCE.adaptor = this;
    this.activity = activity;
    this.webView = webView;

    Context context = activity.getApplicationContext();

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.addJavascriptInterface(this, "PostcardApplication");
    webView.loadUrl("file:///android_asset/www/index.html");

    this.properties = new Properties();
    String propFileName = "postcard.properties";

    try {
        InputStream inputStream = context.getAssets().open(propFileName);
        if (inputStream != null) {
            this.properties.load(inputStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.networkAccountDataSource = new NetworkAccountDataSource(context);
    this.networkAccountDataSource.open();

    this.personDataSource = new PersonDataSource(context);
    this.personDataSource.open();

    this.tagDataSource = new TagDataSource(context);
    this.tagDataSource.open();
}

From source file:ar.com.lapotoca.resiliencia.gallery.ui.ImageDetailActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.image_menu, menu);
    MenuItem shareItem = menu.findItem(R.id.menu_share);
    shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override/*from   w  ww  . j  a  v a 2  s.  com*/
        public boolean onMenuItemClick(MenuItem item) {
            try {

                ImageHolder img = Images.image[mPager.getCurrentItem()];
                if (img == null) {
                    return false;
                }

                AnalyticsHelper.getInstance().sendImageShareEvent(img.getUrl());

                Uri bmpUri;
                if (img.isLocal()) {
                    bmpUri = Uri.parse("content://" + AssetProvider.CONTENT_URI + "/" + img.getUrl());
                } else {
                    ImageView iv = (ImageView) findViewById(R.id.picImageView);
                    bmpUri = getLocalBitmapUri(iv);
                }
                if (bmpUri != null) {
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
                    shareIntent.setType("image/*");
                    startActivity(Intent.createChooser(shareIntent, getString(R.string.share_item)));

                    AnalyticsHelper.getInstance().sendImageShareCompleted();
                    return true;
                } else {

                    AnalyticsHelper.getInstance().sendImageShareCanceled();
                    return false;
                }
            } catch (Exception e) {
                AnalyticsHelper.getInstance().sendImageShareFailed(e.getMessage());
                return false;
            }
        }
    });

    MenuItem downloadItem = menu.findItem(R.id.download_asset);
    downloadItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

            Context context = ImageDetailActivity.this;

            String appDirectoryName = context.getString(R.string.app_name);
            File imageRoot = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            ImageHolder img = Images.image[mPager.getCurrentItem()];
            if (img == null) {
                return false;
            }

            AssetManager assetManager = context.getAssets();
            try {
                InputStream is = assetManager.open(img.getUrl());
                String fileName = img.getUrl().split("/")[1];

                imageRoot.mkdirs();
                File image = new File(imageRoot, fileName);

                byte[] buffer = new byte[BUFFER_LENGHT];
                FileOutputStream fos = new FileOutputStream(image);
                int read = 0;

                while ((read = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, read);
                }

                fos.flush();
                fos.close();
                is.close();

                String[] paths = { image.getAbsolutePath() };

                MediaScannerConnection.scanFile(context, paths, null, null);
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_image_succesfull));
                AnalyticsHelper.getInstance().sendDownloadImage(fileName);

            } catch (Exception e) {
                NotificationHelper.showNotification(context,
                        context.getString(R.string.download_no_permissions));
                AnalyticsHelper.getInstance().sendImageDownloadFailed(e.getMessage());
            }

            return true;
        }
    });

    return true;
}

From source file:com.gnuroot.debian.GNURootMain.java

private void copyAssets(String packageName) {
    Context friendContext = null;
    try {//from   w  ww .  j  ava  2s.  co m
        friendContext = this.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
    } catch (NameNotFoundException e1) {
        return;
    }
    AssetManager assetManager = friendContext.getAssets();
    File tempFile = new File(getInstallDir().getAbsolutePath() + "/support");
    if (!tempFile.exists()) {
        tempFile.mkdir();
    }
    String[] files = null;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            filename = filename.replace(".mp2", "");
            filename = filename.replace(".mp3", ".tar.gz");
            File outFile = new File(tempFile, filename);
            out = new FileOutputStream(outFile);
            if (filename.contains(".tar.gz"))
                out = openFileOutput(filename, MODE_PRIVATE);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
            exec("chmod 0777 " + outFile.getAbsolutePath(), true);
        } catch (IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }
    }
}

From source file:de.dhbw.advisory.recipe.RecipeFragment.java

@Override
public void onAttach(Context context) {
    Log.i("Recipe-Fragment - onAttach", "Methode gestartet");
    super.onAttach(context);
    //Der Developer key wird spter aus der properties-Datei ausgelesen
    Properties properties = new Properties();

    try {/*from  www.ja v  a 2 s.c o  m*/
        //Hier wird der API-Key geladen
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = assetManager.open("apikey.properties");
        properties.load(inputStream);
        apiKey = properties.getProperty("spoonacular.apikey");
    } catch (IOException e) {
        //Falls das Fragment nicht geladen werden konnte
        Toast.makeText(context, "Fragment konnte nicht geladen werden", Toast.LENGTH_SHORT).show();
    }
    Log.i("Recipe-Fragment - onAttach", "Methode beendet");
}

From source file:com.rukman.emde.smsgroups.platform.GMSContactOperations.java

public static long addGroupToContacts(Context context, ContentProviderClient provider, Account account,
        JSONObject group, SyncResult result)
        throws RemoteException, OperationApplicationException, JSONException {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
            .withValue(RawContacts.ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE)
            .withValue(RawContacts.ACCOUNT_NAME, account.name)
            .withValue(RawContacts.SOURCE_ID, group.getString(JSONKeys.KEY_ID));
    ops.add(op.build());//from ww w . jav a2s .c  o  m
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, group.getString(JSONKeys.KEY_NAME));
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(CommonDataKinds.Phone.NUMBER, group.get(JSONKeys.KEY_PHONE))
            .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MAIN);
    ops.add(op.build());
    op = ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(Data.RAW_CONTACT_ID, 0)
            .withValue(Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE).withYieldAllowed(true);
    ops.add(op.build());
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        is = context.getAssets().open("gms.png", AssetManager.ACCESS_BUFFER);
        baos = new ByteArrayOutputStream();
        int value = is.read();
        while (value != -1) {
            baos.write(value);
            value = is.read();
        }
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
                .withYieldAllowed(true);
        ops.add(op.build());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (baos != null) {
                baos.close();
            }
        } catch (IOException ignore) {
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    return (results[0].uri != null) ? ContentUris.parseId(results[0].uri) : -1L;
}

From source file:com.jsonstore.util.JSONStoreUtil.java

/**
 * This method assumes it will find the library at:
 *     files/featurelibs/{arch}/{library}.zip
 *
 * It will unzip the library to the root folder
 * then see if any other architecture folders exist and delete them since
 * they will never be used on this architecture.
 *
 * @param ctx/* ww  w .ja v  a  2  s.co  m*/
 * @param library example "libcrypto.so.1.0.0"
 *
 *
 */
public static final synchronized void loadLib(Context ctx, String library) {

    // keep track of which libs are already loaded, so we don't process multiple calls for the same lib unnecessarily
    // Notice we use a static.  This means calls to loadLib for the same 'library' parameter will be processed
    // only upon app startup, not app foreground.  We want to keep the behavior for cases where the native app has been
    // updated (through the Play Store, for example) and the target .so file needs to be replaced.

    if (!LOADED_LIBS.contains(library)) {

        // we only support "armeabi" and "x86"
        final String ARMEABI = "armeabi";
        final String X86 = "x86";

        String arch = System.getProperty("os.arch"); // the architecture we're running on
        String nonArch = null; // the architecture we are NOT on
        coreLogger.logDebug("os.arch: " + arch);
        if (arch != null && (arch.toLowerCase().startsWith("i") || arch.toLowerCase().startsWith("x86"))) { // i686, x86_64
            arch = X86;
            nonArch = ARMEABI;
        } else {
            arch = ARMEABI;
            nonArch = X86;
        }

        final String libPath = arch + File.separator + library;

        File nonArchStorage = new File(getNoBackupFilesDir(ctx), nonArch);

        deleteDirectory(nonArchStorage);

        File targetFile = new File(getNoBackupFilesDir(ctx), library);

        // delete the target
        targetFile.delete();

        coreLogger.logDebug("Extracting zip file: " + libPath);
        try {
            InputStream istr = ctx.getAssets().open(libPath + ".zip");
            unpack(istr, targetFile.getParentFile());
        } catch (IOException e) {
            e.printStackTrace();
            coreLogger.logDebug("Error extracting zip file: " + e.getMessage());
        }

        coreLogger.logDebug("Loading library using System.load: " + targetFile.getAbsolutePath());
        System.load(targetFile.getAbsolutePath());
    }

    LOADED_LIBS.add(library);
}