List of usage examples for android.content.res AssetManager open
public @NonNull InputStream open(@NonNull String fileName) throws IOException
From source file:com.facebook.FacebookActivityTestCase.java
protected synchronized void readApplicationIdAndSecret() { synchronized (FacebookTestCase.class) { if (applicationId != null && applicationSecret != null && clientToken != null) { return; }/* ww w. j av a 2 s. c om*/ AssetManager assets = getInstrumentation().getTargetContext().getResources().getAssets(); InputStream stream = null; final String errorMessage = "could not read applicationId and applicationSecret from config.json; ensure " + "you have run 'configure_unit_tests.sh'. Error: "; try { stream = assets.open("config.json"); String string = Utility.readStreamToString(stream); JSONTokener tokener = new JSONTokener(string); Object obj = tokener.nextValue(); if (!(obj instanceof JSONObject)) { fail(errorMessage + "could not deserialize a JSONObject"); } JSONObject jsonObject = (JSONObject) obj; applicationId = jsonObject.optString("applicationId"); applicationSecret = jsonObject.optString("applicationSecret"); clientToken = jsonObject.optString("clientToken"); if (Utility.isNullOrEmpty(applicationId) || Utility.isNullOrEmpty(applicationSecret) || Utility.isNullOrEmpty(clientToken)) { fail(errorMessage + "config values are missing"); } } catch (IOException e) { fail(errorMessage + e.toString()); } catch (JSONException e) { fail(errorMessage + e.toString()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { fail(errorMessage + e.toString()); } } } } }
From source file:com.larvalabs.svgandroid.SVGParser.java
/** * Parse SVG data from an Android application asset. * @param assetMngr the Android asset manager. * @param svgPath the path to the SVG file in the application's assets. * @return the parsed SVG./*from w w w . jav a 2 s .com*/ * @throws SVGParseException if there is an error while parsing. * @throws IOException if there was a problem reading the file. */ public static SVG getSVGFromAsset(AssetManager assetMngr, String svgPath) throws SVGParseException, IOException { InputStream inputStream = assetMngr.open(svgPath); SVG svg = getSVGFromInputStream(inputStream); inputStream.close(); return svg; }
From source file:org.mozilla.gecko.tests.BaseTest.java
public InputStream getAsset(String filename) throws IOException { AssetManager assets = getInstrumentation().getContext().getAssets(); return assets.open(filename); }
From source file:com.larvalabs.svgandroid.SVGParser.java
/** * Parse SVG data from an Android application asset. * @param assetMngr the Android asset manager. * @param svgPath the path to the SVG file in the application's assets. * @param searchColor the color in the SVG to replace. * @param replaceColor the color with which to replace the search color. * @return the parsed SVG.//from w ww . j a v a 2 s .c o m * @throws SVGParseException if there is an error while parsing. * @throws IOException if there was a problem reading the file. */ public static SVG getSVGFromAsset(AssetManager assetMngr, String svgPath, int searchColor, int replaceColor) throws SVGParseException, IOException { InputStream inputStream = assetMngr.open(svgPath); SVG svg = getSVGFromInputStream(inputStream, searchColor, replaceColor); inputStream.close(); return svg; }
From source file:com.google.blockly.android.BlocklyActivityHelper.java
/** * Resets the {@link BlockFactory} with the provided block definitions and extensions. * @param blockDefinitionsJsonPaths The list of definition asset paths. * @param blockExtensions The extensions supporting the block definitions. * @throws IllegalStateException On any issues with the input. *//* w ww .j a va 2 s . co m*/ public void resetBlockFactory(@Nullable List<String> blockDefinitionsJsonPaths, @Nullable Map<String, BlockExtension> blockExtensions) { AssetManager assets = mActivity.getAssets(); BlockFactory factory = mController.getBlockFactory(); factory.clear(); String assetPath = null; try { if (blockExtensions != null) { for (String id : blockExtensions.keySet()) { factory.registerExtension(id, blockExtensions.get(id)); } } if (blockDefinitionsJsonPaths != null) { for (String path : blockDefinitionsJsonPaths) { assetPath = path; factory.addJsonDefinitions(assets.open(path)); } } } catch (IOException | BlockLoadingException e) { throw new IllegalStateException("Failed to load block definition asset file: " + assetPath, e); } }
From source file:it.geosolutions.geocollect.android.core.mission.PendingMissionListActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (BuildConfig.DEBUG) { Log.v(TAG, "onCreate()"); }/*from w w w. j a va 2s . c om*/ // Load the application properties file Properties properties = new Properties(); try { // access to the folder assets AssetManager am = getAssets(); // opening the file InputStream inputStream = am.open("geocollect.properties"); // loading of the properties properties.load(inputStream); } catch (IOException e) { Log.e(GeoCollectApplication.class.getSimpleName(), e.toString()); } // Get the NewRelic token, if found start the monitoring String newRelicToken = properties.getProperty("newRelicToken"); if (newRelicToken != null) { NewRelic.withApplicationToken(newRelicToken).start(this); } // Login data is always necessary to load mission data final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); final String authKey = prefs.getString(LoginActivity.PREFS_AUTH_KEY, null); if (savedInstanceState == null && (getIntent() == null || !getIntent().hasExtra(KEY_NAVIGATING_UP))) { shouldStartMap = getStartAsMap(); } else { shouldStartMap = false; } if (authKey == null) { startActivityForResult(new Intent(this, LoginActivity.class), LoginActivity.REQUEST_LOGIN); shouldStartMap = false; } else if (!Once.beenDone(TimeUnit.MINUTES, UPDATE_MISSIONS_TIME_AMOUNT, UPDATE_MISSIONS) && NetworkUtil.isOnline(getBaseContext())) { if (BuildConfig.DEBUG) { Log.d(TAG, "fetching remote Templates"); } final TemplateDownloadTask task = new TemplateDownloadTask() { @Override public void complete(final ArrayList<MissionTemplate> downloadedTemplates) { /** * download successful, elaborate result **/ // 1. update database ArrayList<MissionTemplate> validTemplates = new ArrayList<MissionTemplate>(); if (downloadedTemplates != null && downloadedTemplates.size() > 0) { if (spatialiteDatabase == null) { spatialiteDatabase = SpatialiteUtils.openSpatialiteDB(PendingMissionListActivity.this, "geocollect/genova.sqlite"); } for (MissionTemplate t : downloadedTemplates) { if (!PersistenceUtils.createOrUpdateTablesForTemplate(t, spatialiteDatabase)) { Log.w(TAG, "error creating/updating table"); } else { // if insert succesfull add to list of valid templates validTemplates.add(t); } } } Log.d(TAG, "database updated"); // 2. save valid templates PersistenceUtils.saveDownloadedTemplates(getBaseContext(), validTemplates); if (BuildConfig.DEBUG) { Log.d(TAG, "valid templates persisted"); } // 3. update navdrawer menu runOnUiThread(new Runnable() { @Override public void run() { navConf = getNavDrawerConfiguration(); mDrawerList.setAdapter(navConf.getBaseAdapter()); Log.d(TAG, "navdrawer updated"); } }); Once.markDone(UPDATE_MISSIONS); } }; String username = prefs.getString(LoginActivity.PREFS_USER_EMAIL, null); String password = prefs.getString(LoginActivity.PREFS_PASSWORD, null); String authorizationString = LoginRequestInterceptor.getB64Auth(username, password); task.execute(authKey, authorizationString); } // Default template // Initialize database // This should be the first thing the Activity does if (spatialiteDatabase == null) { spatialiteDatabase = SpatialiteUtils.openSpatialiteDB(this, "geocollect/genova.sqlite"); if (spatialiteDatabase != null && !spatialiteDatabase.dbversion().equals("unknown")) { MissionTemplate t = MissionUtils.getDefaultTemplate(this); if (!PersistenceUtils.createOrUpdateTablesForTemplate(t, spatialiteDatabase)) { Log.e(TAG, "error creating/updating tables for " + t.nameField); } HashMap<String, ArrayList<String>> uploadables = PersistenceUtils.loadUploadables(this); if (uploadables != null && uploadables.size() > 0) { PersistenceUtils.sanitizePendingFeaturesList(uploadables, spatialiteDatabase); PersistenceUtils.saveUploadables(this, uploadables); } } } // Set the layout getLayoutInflater().inflate(R.layout.activity_pendingmission_list, (FrameLayout) findViewById(R.id.content_frame)); if (findViewById(R.id.pendingmission_detail_container) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. mTwoPane = true; // In two-pane mode, list items should be given the // 'activated' state when touched. ((PendingMissionListFragment) getSupportFragmentManager().findFragmentById(R.id.pendingmission_list)) .setActivateOnItemClick(true); } }
From source file:net.smart_json_database.JSONDatabase.java
private JSONDatabase(Context context, String configurationName) throws InitJSONDatabaseExcepiton { AssetManager assetManager = context.getAssets(); InputStream stream = null;/*from ww w .ja va2s . co m*/ String configXML = null; try { configXML = configurationName + ".xml"; stream = assetManager.open(configXML); } catch (IOException e) { throw new InitJSONDatabaseExcepiton("Could not load asset " + configXML); } finally { if (stream != null) { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLConfigHandler handler = new XMLConfigHandler(); SAXParser saxparser; try { saxparser = factory.newSAXParser(); saxparser.parse(stream, handler); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block throw new InitJSONDatabaseExcepiton("Parser-Error while reading the " + configXML, e); } catch (SAXException e) { // TODO Auto-generated catch block throw new InitJSONDatabaseExcepiton("SAX-Error while reading the " + configXML, e); } catch (IOException e) { // TODO Auto-generated catch block throw new InitJSONDatabaseExcepiton("IO-Error while reading the " + configXML, e); } mDbName = handler.getDbName(); if (Util.IsNullOrEmpty(mDbName)) throw new InitJSONDatabaseExcepiton("db name is empty check the xml configuration"); mDbVersion = handler.getDbVersion(); if (mDbVersion < 1) throw new InitJSONDatabaseExcepiton( "db version must be 1 or greater - check the xml configuration"); mUpgradeClassPath = handler.getUpgradeClass(); if (!Util.IsNullOrEmpty(mUpgradeClassPath)) { try { Class<?> x = Class.forName(mUpgradeClassPath); dbUpgrade = (IUpgrade) x.newInstance(); } catch (Exception e) { } } dbHelper = new DBHelper(context, mDbName, mDbVersion); listeners = new ArrayList<IDatabaseChangeListener>(); tags = new HashMap<String, Integer>(); invertedTags = new HashMap<Integer, String>(); updateTagMap(); } else { throw new InitJSONDatabaseExcepiton(configXML + " is empty"); } } }
From source file:com.xrmaddness.offthegrid.ListActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivityForResult(intent, SETTINGS_DONE); return true; case R.id.action_my_fingerprint: { String fingerprint;//w w w . j ava2 s. c o m if (pgp == null) { fingerprint = "No keys available, fill in email address first in settings"; } else { fingerprint = pgp.fingerprint(pgp.my_user_id); if (fingerprint == null) { fingerprint = "No key found"; } } AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setMessage(fingerprint); alert.setTitle(R.string.action_my_fingerprint); alert.setPositiveButton("OK", null); alert.setCancelable(true); alert.create().show(); return true; } case R.id.action_add_contact: { if (pgp == null) return true; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(R.string.action_add_contact); alert.setMessage(R.string.dialog_add_contact); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); Log.d("add_contact", value); add_contact(value); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); return true; } case R.id.action_add_group: { if (pgp == null) return true; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(R.string.action_add_group); alert.setMessage(R.string.dialog_add_group); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_TEXT); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); Log.d("add_group", value); add_group(value); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); return true; } case R.id.action_show_license: { String license = version_get() + "\n"; AssetManager am = getAssets(); InputStream is; try { is = am.open("license.txt"); license += filestring.is2str(is); is.close(); is = am.open("spongycastle_license.txt"); license += filestring.is2str(is); is.close(); is = am.open("javamail_license.txt"); license += filestring.is2str(is); is.close(); } catch (IOException e) { Log.e("show license", e.getMessage()); } AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setMessage(license); alert.setTitle(R.string.action_show_license); alert.setPositiveButton("OK", null); alert.setCancelable(true); alert.create().show(); return true; } default: return super.onOptionsItemSelected(item); } }
From source file:com.shurik.droidzebra.ZebraEngine.java
private void _asset2File(String[] assets, File file) throws IOException { if (!file.exists() || file.length() == 0) { // copy files AssetManager assetManager = mContext.getAssets(); InputStream source = null; OutputStream destination = null; try {/* www . j a v a2 s.c o m*/ destination = new FileOutputStream(file); for (String sourceAsset : assets) { source = assetManager.open(sourceAsset); byte[] buffer = new byte[1024]; int len = source.read(buffer); while (len != -1) { destination.write(buffer, 0, len); len = source.read(buffer); } } } finally { if (destination != null) { try { destination.close(); } catch (IOException e) { fatalError(e.getMessage()); } } } } }