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:org.cnx.openstaxcnxmusic.fragments.LandingListFragment.java

private BookList readJson() {
    AssetManager assets = getActivity().getAssets();
    BookList aboutList = new BookList();

    Gson gson = new Gson();

    try {//  w w  w .  ja va  2 s .  c  om
        InputStream is = assets.open("bookList.json");
        BufferedReader bf = new BufferedReader(new InputStreamReader(is));
        aboutList = gson.fromJson(bf, BookList.class);
    } catch (IOException ioe) {
        Log.d("json", "Some problem: " + ioe.toString());
    }

    Collections.sort(aboutList.getBookList());

    return aboutList;
}

From source file:com.adsoft.girls_tatoos_gallery.MainActivity.java

private Bitmap getBitmapFromAsset(String strName) {
    AssetManager assetManager = getResources().getAssets();
    InputStream istr = null;//from   ww w .  j  av  a2s. co  m
    Bitmap bitmap = null;
    try {
        istr = assetManager.open("images/" + strName);
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = 2;
        bitmap = BitmapFactory.decodeStream(istr, new Rect(), o2);
        istr.close();
        istr = null;
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(MainActivity.this, "Exeption", Toast.LENGTH_SHORT).show();
    }

    return bitmap;
}

From source file:com.ibm.mobilefirst.mobileedge.interpretation.Classification.java

private String getFileAsString(Context context, String filename) {
    AssetManager assetManager = context.getAssets();
    try {/*from w w w.java  2  s . co m*/
        InputStream inputStream = assetManager.open(filename);
        return getStringFromInputStream(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.intel.xdk.base.Base.java

private Bitmap getBitmapFromAsset(String strName) throws IOException {
    AssetManager assetManager = cordova.getActivity().getAssets();
    InputStream istr = assetManager.open(strName);
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}

From source file:org.openlmis.core.persistence.Migration.java

protected void execSQLScript(String filename) {
    AssetManager manager = LMISApp.getContext().getResources().getAssets();

    String path = DIR_MIGRATION + File.separator + filename;
    db.beginTransaction();//  www . j a  v a2  s . co  m
    try {
        InputStream io = manager.open(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(io));

        String line = reader.readLine();
        while (line != null) {
            String cmd = line.trim();
            if (!StringUtils.isEmpty(cmd)) {
                execSQL(cmd);
            }
            line = reader.readLine();
        }
        reader.close();

        db.setTransactionSuccessful();
    } catch (IOException e) {
        new LMISException(e).reportToFabric();
        throw new RuntimeException("Invalid migration file :" + filename);
    } finally {
        db.endTransaction();
    }
}

From source file:com.ameron32.apps.tapnotes.MainActivity.java

@Override
protected Bitmap providePaletteImage() {
    final AssetManager assets = getResources().getAssets();
    try {//from w  w w.  j a  v  a 2 s  .  c  o  m
        return BitmapFactory.decodeStream(assets.open("2015ProgramConventionOptimized_1.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    try {//from  www. j  av  a2s .c  o m
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_kai);
        this.context = getApplicationContext();

        database = DataSource.getInstance(context);
        DevSettings devSettings = database.getDevSettings();
        if (devSettings == null) {
            try {
                Resources resources = this.getResources();
                AssetManager assetManager = resources.getAssets();
                InputStream inputStream = assetManager.open("settings.properties");
                Properties properties = new Properties();
                properties.load(inputStream);
                devMode = Boolean.parseBoolean(properties.getProperty("devmode"));
                useHttps = Boolean.parseBoolean(properties.getProperty("useHttps"));
                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();
        }

        bk = BlueKai.getInstance(this, this, devMode, useHttps, siteId, appVersion, this, new Handler());
        bk.setFragmentManager(getSupportFragmentManager());

        keyText = (EditText) findViewById(R.id.keyText);
        valueText = (EditText) findViewById(R.id.valueText);
        //pairsCountText = (EditText) findViewById(R.id.pairs_count);

        clearButton = (Button) findViewById(R.id.clear);
        clearButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                keyText.setText("");
                valueText.setText("");
                keyText.requestFocus();
            }
        });

        sendButton = (Button) findViewById(R.id.send);
        sendButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String key = keyText.getText().toString();
                String value = valueText.getText().toString();
                if (key == null || key.trim().equals("")) {
                    keyText.requestFocus();
                    Toast.makeText(context, "Key is empty. Please enter a value", Toast.LENGTH_LONG).show();
                } else if (value == null || value.trim().equals("")) {
                    valueText.requestFocus();
                    Toast.makeText(context, "Value is empty. Please enter a value", Toast.LENGTH_LONG).show();
                } else {
                    bk.put(key, value);
                }
            }
        });
    } catch (Exception ex) {
        Log.e("BlueKaiTab", "Error while creating", ex);
    }
}

From source file:com.aujur.ebookreader.catalog.DownloadLocalFileTask.java

@Override
protected String doInBackground(String... params) {

    try {/*from   w ww .  ja  va 2  s . c  o m*/

        String url = params[0];
        // url = "vademecum/Editora AuJur/Codigo Civil (1)/Codigo Civil - Editora AuJur.epub";
        // vademecum/Editora AuJur/Codigo Civil (1)/Codigo Civil - Editora AuJur.epub
        LOG.debug("Downloading: " + url);

        String fileName = url.substring(url.lastIndexOf('/') + 1);
        fileName = fileName.replaceAll("\\?|&|=", "_");

        File destFolder = new File(config.getDownloadsFolder());
        if (!destFolder.exists()) {
            destFolder.mkdirs();
        }

        /**
         * Make sure we always store downloaded files as .epub, so they show
         * up in scans later on.
         */
        if (!fileName.endsWith(".epub")) {
            fileName = fileName + ".epub";
        }

        destFile = new File(destFolder, URLDecoder.decode(fileName));

        if (destFile.exists()) {
            destFile.delete();
        }

        // lenghtOfFile is used for calculating download progress
        AssetFileDescriptor fd = context.getAssets().openFd(url);

        long lenghtOfFile = fd.getLength();

        // this is where the file will be seen after the download
        FileOutputStream f = new FileOutputStream(destFile);

        try {
            // file input is from the url
            AssetManager assetManager = context.getAssets();
            InputStream in = assetManager.open(url);

            // here's the download code
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0 && !isCancelled()) {

                // Make sure the user can cancel the download.
                if (isCancelled()) {
                    return null;
                }

                total += len1;
                publishProgress(total, lenghtOfFile, (long) ((total * 100) / lenghtOfFile));
                f.write(buffer, 0, len1);
            }
        } finally {
            f.close();
        }

        if (!isCancelled()) {
            // FIXME: This doesn't belong here really...
            Book book = new EpubReader().readEpubLazy(destFile.getAbsolutePath(), "UTF-8");
            libraryService.storeBook(destFile.getAbsolutePath(), book, false, config.isCopyToLibrayEnabled());
        }

    } catch (Exception e) {
        LOG.error("Download failed.", e);
        this.failure = e;
    }

    return null;
}

From source file:org.uribeacon.beacon.UriBeaconTest.java

public void testUriBeaconTestData() throws JSONException, IOException {
    Context context = getContext();
    AssetManager am = context.getAssets();
    JSONObject testObject = inputJson(am.open("testdata.json"));
    JSONArray testData = testObject.getJSONArray("test-data");
    for (int i = 0; i < testData.length(); i++) {
        JSONObject encodingTest = testData.getJSONObject(i);

        String uri = encodingTest.getString("url");
        assertNotNull(uri);//from www .j av  a  2  s .  c  om
        Integer txPowerLevel = encodingTest.optInt("tx", 20);
        Integer flags = encodingTest.optInt("flags", 0);
        UriBeacon uriBeacon;
        try {
            uriBeacon = new UriBeacon.Builder().uriString(uri).txPowerLevel(txPowerLevel.byteValue())
                    .flags(flags.byteValue()).build();
        } catch (URISyntaxException e) {
            uriBeacon = null;
        }
        JSONArray scanRecordJson = encodingTest.optJSONArray("scanRecord");
        if (scanRecordJson == null || uriBeacon == null) {
            assertNull("Null assert failed for uriBeacon", scanRecordJson);
            assertNull("Null assert failed for " + uriBeacon, uriBeacon);
        } else {
            byte[] scanRecord = jsonToByteArray(scanRecordJson);
            byte[] uriBeaconScanRecord = uriBeacon.toByteArray();
            MoreAsserts.assertEquals(scanRecord, uriBeaconScanRecord);
        }
    }
}

From source file:com.example.amitgupta.shinobiCharts.CandlestickActivity.java

private List<Data<Date, Double>> LoadStockPriceData(String assetName) {
    List<Data<Date, Double>> dataPoints = new ArrayList<Data<Date, Double>>();
    AssetManager assetManager = this.getAssets();
    InputStream stream = null;//from   www  .j av  a  2s.co m
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
    try {
        stream = assetManager.open(assetName);
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));

        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            MultiValueDataPoint<Date, Double> dataPoint = new MultiValueDataPoint<Date, Double>(
                    formatter.parse(jsonObject.getString("date")), jsonObject.getDouble("low"),
                    jsonObject.getDouble("high"), jsonObject.getDouble("open"), jsonObject.getDouble("close"));
            dataPoints.add(dataPoint);
        }
    } catch (IOException exc) {
        Log.e("CandlestickChart", "Unable to load asset");
    } catch (JSONException exc) {
        Log.e("CandlestickChart", "Unable to parse JSON data");
    } catch (ParseException exc) {
        Log.e("CandlestickChart", "Unable to parse JSON data");
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException exc) {
            }
        }
    }
    return dataPoints;
}