Example usage for android.content.res AssetManager list

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

Introduction

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

Prototype

public @Nullable String[] list(@NonNull String path) throws IOException 

Source Link

Document

Return a String array of all the assets at the given path.

Usage

From source file:org.chromium.ChromeI18n.java

private boolean isLocaleAvailable(String locale) throws IOException {
    List<String> availableLocales = new ArrayList<String>();
    AssetManager am = this.cordova.getActivity().getAssets();
    String[] localesArr = am.list("www/locales");
    for (String currLocale : localesArr) {
        try {//  w  w w.j av  a 2  s . c o  m
            // Check that the manifest.json exists
            InputStream is = am.open("www/locales/" + currLocale + "/messages.json");
            is.close();
            availableLocales.add(currLocale);
        } catch (IOException e) {
            /* Suppress not found exceptions */ }
    }
    return availableLocales.contains(locale);
}

From source file:com.mousebird.maply.MaplyStarModel.java

public MaplyStarModel(String fileName, String imageName, Activity activity) throws IOException {
    AssetManager assetMgr = activity.getAssets();
    InputStream inputStream = null;
    String[] paths = assetMgr.list("maplystarmodel");
    for (String path : paths) {
        if (path.equals(imageName)) {
            //image
            BufferedInputStream bufferedInputStream = null;
            try {
                inputStream = assetMgr.open("maplystarmodel/" + path);
                bufferedInputStream = new BufferedInputStream(inputStream);
                image = BitmapFactory.decodeStream(bufferedInputStream);
            } finally {
                if (bufferedInputStream != null) {
                    try {
                        bufferedInputStream.close();
                    } catch (IOException e) {
                    }/*w  w  w .j  av  a 2  s  . c  om*/
                }
            }
        }
        if (path.equals(fileName)) {
            //data
            Matcher m;
            try {
                inputStream = assetMgr.open("maplystarmodel/" + path);
                String stars = IOUtils.toString(inputStream, Charset.defaultCharset());
                Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
                m = p.matcher(stars);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
            }

            this.stars = new ArrayList<SingleStar>();
            if (m.groupCount() % 3 == 0) {
                int i = 0;
                SingleStar s = null;
                while (m.find()) {
                    switch (i) {
                    case 0:
                        s = new SingleStar();
                        s.ra = Float.valueOf(m.group());
                        i++;
                        break;
                    case 1:
                        s.dec = Float.valueOf(m.group());
                        i++;
                        break;
                    case 2:
                        s.mag = Float.valueOf(m.group());
                        this.stars.add(s);
                        i = 0;
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    }
}

From source file:de.geeksfactory.opacclient.OpacClient.java

public List<Library> getLibraries(ProgressCallback callback) throws IOException {
    AssetManager assets = getAssets();
    String[] files = assets.list(ASSETS_BIBSDIR);
    int num = files.length;

    List<Library> libs = new ArrayList<>();

    StringBuilder builder;/* w  w w  . j a v  a  2s. c om*/
    BufferedReader reader;
    InputStream fis;
    String line;
    String json;

    for (int i = 0; i < num; i++) {
        builder = new StringBuilder();
        fis = assets.open(ASSETS_BIBSDIR + "/" + files[i]);

        reader = new BufferedReader(new InputStreamReader(fis, "utf-8"));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        fis.close();
        json = builder.toString();
        try {
            Library lib = Library.fromJSON(files[i].replace(".json", ""), new JSONObject(json));
            if (!lib.getApi().equals("test") || BuildConfig.DEBUG)
                libs.add(lib);
        } catch (JSONException e) {
            Log.w("JSON library files", "Failed parsing library " + files[i]);
            e.printStackTrace();
        }
        if (callback != null && i % 100 == 0 && i > 0) {
            // reporting progress for every 100 loaded files should be enough
            callback.publishProgress(((double) i) / num);
        }
    }

    return libs;
}

From source file:cycronix.CTandroid.CTAserver.java

private void copyAssets() {
    AssetManager assetManager = getApplicationContext().getAssets();

    String[] files = null;/*from w w  w .jav  a2 s. c  o  m*/
    try {
        files = assetManager.list(resourceFolder); // folder name
    } catch (Exception e) {
        Log.e(TAG, "ERROR: " + e.toString());
    }

    File directory = new File(Environment.getExternalStorageDirectory() + "/" + resourceFolder);
    directory.mkdirs();

    for (int i = 0; i < files.length; i++) {
        try {
            InputStream in = assetManager.open("CTweb/" + files[i]);
            OutputStream out = new FileOutputStream(
                    Environment.getExternalStorageDirectory() + "/" + resourceFolder + "/" + files[i]);
            byte[] buffer = new byte[65536];
            int read;
            while ((read = in.read(buffer)) > 0)
                out.write(buffer, 0, read);
            in.close();
            out.flush();
            out.close();
            Log.d(TAG, "Asset file copied to SD card: " + files[i]);
        } catch (Exception e) {
            Log.e(TAG, "ERROR: " + e.toString());
        }
    }
}

From source file:org.n52.geoar.GeoARActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from  w  w w  .  j a  va 2 s  . c o m*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    AssetManager assetManager = getAssets();
    String[] files;
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (savedInstanceState == null) {
        // First time init
        Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.info_use);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.ok, null);
        builder.setTitle(R.string.advice);
        builder.show();
    }

    if (GeoARApplication.checkAppFailed()) {
        // App Failed
        Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.info_failed_email);
        builder.setCancelable(true);
        builder.setPositiveButton(getString(R.string.send_report), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                GeoARApplication.sendFailMail(GeoARActivity.this);
                GeoARApplication.clearAppFailed();
            }
        });
        builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                GeoARApplication.clearAppFailed();
            }
        });
        builder.setTitle(R.string.sorry);
        builder.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                GeoARApplication.clearAppFailed();
            }
        });
        builder.show();
    }

    Fragment fragmentToShow = mMapFragment;
    if (savedInstanceState != null) {
        String currentFragmentClassName = savedInstanceState.getString(CURRENT_FRAGMENT_KEY);
        if (currentFragmentClassName != null) {
            for (Fragment fragment : mFragments) {
                if (fragment.getClass().getSimpleName().equals(currentFragmentClassName)) {
                    fragmentToShow = fragment;
                    break;
                }
            }
        }

    }
    showFragment(fragmentToShow);

    RealityCamera.restoreState();

    if (savedInstanceState != null) {
        // restore manual positioning
        LocationHandler.onRestoreInstanceState(savedInstanceState);
    }

    IntroController.initPopupShow(this);

    // // TODO Debug only
    // LocationHandler.setManualLocation(new GeoLocation(51.965344,
    // 7.600003));

}

From source file:org.runnerup.view.MainLayout.java

void handleBundled(AssetManager mgr, String srcBase, String dstBase) {
    String list[] = null;/*from   w w w  .j a va  2 s . co  m*/

    try {
        list = mgr.list(srcBase);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (list != null) {
        for (String add : list) {
            boolean isFile = false;

            String src = srcBase + File.separator + add;
            String dst = dstBase + File.separator + add;
            try {
                InputStream is = mgr.open(src);
                is.close();
                isFile = true;
            } catch (Exception ex) {
                //Normal, src is directory for first call
            }

            Log.v(getClass().getName(), "Found: " + src + ", " + dst + ", isFile: " + isFile);

            if (!isFile) {
                //The request is hierarchical, source is still on a directory level
                File dstDir = new File(dstBase);
                dstDir.mkdir();
                if (!dstDir.isDirectory()) {
                    Log.w(getClass().getName(),
                            "Failed to copy " + src + " as \"" + dstBase + "\" is not a directory!");
                    continue;
                }
                handleBundled(mgr, src, dst);
            } else {
                //Source is a file, ready to copy
                File dstFile = new File(dst);
                if (dstFile.isDirectory() || dstFile.isFile()) {
                    Log.v(getClass().getName(), "Skip: " + dst + ", isDirectory(): " + dstFile.isDirectory()
                            + ", isFile(): " + dstFile.isFile());
                    continue;
                }

                //Only copy if the key do not exist already
                String key = "install_bundled_" + add;
                SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
                if (pref.contains(key)) {
                    Log.v(getClass().getName(), "Skip already existing pref: " + key);
                    continue;
                }

                pref.edit().putBoolean(key, true).commit();

                Log.v(getClass().getName(), "Copying: " + dst);
                InputStream input = null;
                try {
                    input = mgr.open(src);
                    FileUtil.copy(input, dst);
                    handleHooks(add);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    FileUtil.close(input);
                }
            }
        }
    }
}

From source file:org.adblockplus.android.Preferences.java

/**
 * Copies file assets from installation package to filesystem.
 *///from   w ww.  j a v a2  s  .  c om
private void copyAssets() {
    final AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("install");
    } catch (final IOException e) {
        Log.e(TAG, "Failed to get assets list", e);
    }
    for (int i = 0; i < files.length; i++) {
        try {
            Log.d(TAG, "Copy: install/" + files[i]);
            final InputStream in = assetManager.open("install/" + files[i]);
            final OutputStream out = openFileOutput(files[i], MODE_PRIVATE);
            final byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            out.flush();
            out.close();
        } catch (final Exception e) {
            Log.e(TAG, "Asset copy error", e);
        }
    }
}

From source file:org.catrobat.catroid.ui.MainMenuActivity.java

private void copyProgramZip() {
    AssetManager assetManager = getResources().getAssets();
    String[] files = null;/* w  w  w. j  av a 2 s.c  o m*/
    try {
        files = assetManager.list("");
    } catch (IOException e) {
        Log.e("STANDALONE", "Failed to get asset file list.", e);
    }
    for (String filename : files) {
        if (filename.contains(ZIP_FILE_NAME)) {
            InputStream in;
            OutputStream out;
            try {
                in = assetManager.open(filename);
                File outFile = new File(Constants.DEFAULT_ROOT, filename);
                out = new FileOutputStream(outFile);
                copyFile(in, out);
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                Log.e("STANDALONE", "Failed to copy asset file: " + filename, e);
            }
        }
    }
}

From source file:com.door43.translationstudio.SettingsActivity.java

/**
 * Shows the simplified settings UI if the device configuration if the
 * device configuration dictates that a simplified, single-pane UI should be
 * shown.//  www. j a v a  2  s.  co m
 */
private void setupSimplePreferencesScreen() {
    if (!isSimplePreferences(this)) {
        return;
    }

    // In the simplified UI, fragments are not used at all and we instead
    // use the older PreferenceActivity APIs.

    // Add 'general' preferences.
    addPreferencesFromResource(R.xml.general_preferences);

    // NOTE: this is a copy paste from GeneralPreferenceFragment
    // identify all typefaces in the assets directory
    AssetManager am = getResources().getAssets();
    String fileList[] = null;
    ArrayList<String> entries = new ArrayList<String>();
    ArrayList<String> entryValues = new ArrayList<String>();
    try {
        fileList = am.list("fonts");
    } catch (IOException e) {
        Logger.e(this.getClass().getName(), "failed to load font assets", e);
    }
    if (fileList != null) {
        for (int i = 0; i < fileList.length; i++) {
            File typeface = AppContext.context().getAssetAsFile("fonts/" + fileList[i]);
            if (typeface != null) {
                TTFAnalyzer analyzer = new TTFAnalyzer();
                String fontname = "";
                fontname = analyzer.getTtfFontName(typeface.getAbsolutePath());
                if (fontname == null) {
                    fontname = FilenameUtils.removeExtension(typeface.getName());
                }
                entries.add(fontname);
                entryValues.add(fileList[i]);
            }
        }
    }

    ListPreference pref = (ListPreference) findPreference(KEY_PREF_TRANSLATION_TYPEFACE);
    pref.setEntries(entries.toArray(new CharSequence[entries.size()]));
    pref.setEntryValues(entryValues.toArray(new CharSequence[entryValues.size()]));
    bindPreferenceSummaryToValue(pref);

    // Add 'sharing' preferences, and a corresponding header.
    //        PreferenceCategory preferenceHeader = new PreferenceCategory(this);
    //        preferenceHeader.setTitle(R.string.pref_header_sharing);
    //        getPreferenceScreen().addPreference(preferenceHeader);
    //        addPreferencesFromResource(R.xml.sharing_preferences);

    // Add 'server' preferences, and a corresponding header.
    PreferenceCategory preferenceHeader = new PreferenceCategory(this);
    preferenceHeader.setTitle(R.string.pref_header_synchronization);
    getPreferenceScreen().addPreference(preferenceHeader);
    addPreferencesFromResource(R.xml.server_preferences);

    // Add 'legal' preferences, and a corresponding header.
    preferenceHeader = new PreferenceCategory(this);
    preferenceHeader.setTitle(R.string.pref_header_legal);
    getPreferenceScreen().addPreference(preferenceHeader);
    addPreferencesFromResource(R.xml.legal_preferences);

    // add 'advanced' preferences and coresponding hreader
    preferenceHeader = new PreferenceCategory(this);
    preferenceHeader.setTitle(R.string.pref_header_advanced);
    getPreferenceScreen().addPreference(preferenceHeader);
    addPreferencesFromResource(R.xml.advanced_preferences);

    // bind the correct legal document to the preference intent
    bindPreferenceClickToLegalDocument(findPreference("license_agreement"), R.string.license);
    bindPreferenceClickToLegalDocument(findPreference("statement_of_faith"), R.string.statement_of_faith);
    bindPreferenceClickToLegalDocument(findPreference("translation_guidelines"),
            R.string.translation_guidlines);
    bindPreferenceClickToLegalDocument(findPreference("software_licenses"), R.string.software_licenses);

    // Bind the summaries of EditText/List/Dialog/Ringtone preferences to
    // their values. When their values change, their summaries are updated
    // to reflect the new value, per the Android Design guidelines.
    //        bindPreferenceSummaryToValue(findPreference(KEY_PREF_AUTOSAVE));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_AUTH_SERVER));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_GIT_SERVER));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_AUTH_SERVER_PORT));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_GIT_SERVER_PORT));
    //        bindPreferenceSummaryToValue(findPreference(KEY_PREF_EXPORT_FORMAT));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_MEDIA_SERVER));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_LOGGING_LEVEL));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_BACKUP_INTERVAL));
    bindPreferenceSummaryToValue(findPreference(KEY_PREF_TYPEFACE_SIZE));
}

From source file:jp.mau.twappremover.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        ScrollView contents = new ScrollView(this);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        contents.addView(layout);/* ww w  .j  av  a 2 s.co  m*/
        AssetManager asm = getResources().getAssets();
        String[] filelist = null;
        try {
            filelist = asm.list("licenses");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (filelist != null) {
            for (String file : filelist) {
                Gen.debug(file);
                InputStream is = null;
                BufferedReader br = null;
                String txt = "";
                try {
                    is = getAssets().open("licenses/" + file);
                    br = new BufferedReader(new InputStreamReader(is));
                    String str;
                    while ((str = br.readLine()) != null) {
                        txt += str + "\n";
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (Exception ex) {
                    }
                    try {
                        if (br != null)
                            br.close();
                    } catch (Exception ex) {
                    }
                }
                TextView tv = new TextView(this);
                tv.setText(txt);
                layout.addView(tv);
            }
        }

        // 
        final PopupView dialog = new PopupView(this);
        dialog.setDialog().setLabels(getString(R.string.activity_main_dlgtitle_oss), "")
                .setView(contents, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setCancelable(true)
                .setPositiveBtn(getString(R.string.activity_main_dlgbtn_oss), new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}