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:se.anyro.tagtider.MainActivity.java

private void loadStations() {

    AssetManager assetManager = getAssets();
    InputStream inputStream = null;
    try {/* w  w  w .j a va2  s.  c o m*/
        inputStream = assetManager.open("stations.json");
    } catch (IOException e) {
        e.printStackTrace();
    }

    String json = StringUtils.readTextFile(inputStream);
    try {
        JSONArray stations = new JSONArray(json);
        mStations = new Station[stations.length()];
        for (int i = 0; i < stations.length(); ++i) {
            JSONObject station = stations.getJSONObject(i);
            mStationNames.add(station.getString("name"));
            mStations[i] = new Station(station);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.phoneremotecontrol.app.http.HttpServerService.java

private boolean copyAsset(AssetManager assetManager, String fromAssetPath, String toPath) {
    InputStream in = null;/*from   www .  ja va  2  s  . c  o m*/
    OutputStream out = null;
    try {
        in = assetManager.open(fromAssetPath);
        new File(toPath).createNewFile();
        out = new FileOutputStream(toPath);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.silverpop.engage.deeplinking.EngageDeepLinkManager.java

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

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

    String line;/* w  w w . j  a v  a 2  s  .  co  m*/
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    return sb.toString();
}

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

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

    String baseUrl = params[0];/*from w  w  w  .  j a  va  2 s .  c  om*/

    if (baseUrl == null || baseUrl.trim().length() == 0) {
        return null;
    }

    boolean isBaseFeed = baseUrl.equals(config.getBaseOPDSFeed());

    baseUrl = baseUrl.trim();

    try {

        AssetManager assetManager = context.getAssets();

        InputStream stream = assetManager.open(baseUrl);
        Feed feed = Nucular.readAtomFeedFromStream(stream);
        feed.setURL(baseUrl);
        feed.setDetailFeed(asDetailsFeed);
        feed.setSearchFeed(asSearchFeed);

        for (Entry entry : feed.getEntries()) {
            entry.setBaseURL(baseUrl);
        }

        if (isBaseFeed) {
            addCustomSitesEntry(feed);
        }

        if (isCancelled()) {
            return null;
        }

        Link searchLink = feed.findByRel(AtomConstants.REL_SEARCH);

        if (searchLink != null) {
            URL mBaseUrl = new URL(baseUrl);
            URL mSearchUrl = new URL(mBaseUrl, searchLink.getHref());
            searchLink.setHref(mSearchUrl.toString());

            LOG.debug("Got searchLink of type " + searchLink.getType() + " with href=" + searchLink.getHref());

            /*
             * Some sites report the search as OpenSearch, but still have
             * the searchTerms in the URL. If the URL already contains
             * searchTerms, we ignore the reported type and treat it as Atom
             */
            if (searchLink.getHref().contains(AtomConstants.SEARCH_TERMS)) {
                searchLink.setType(AtomConstants.TYPE_ATOM);
            }

            if (AtomConstants.TYPE_OPENSEARCH.equals(searchLink.getType())) {

                String searchURL = searchLink.getHref();

                LOG.debug("Attempting to download OpenSearch description from " + searchURL);

                //               try {
                //                  currentRequest = new HttpGet(searchURL);
                //                  InputStream searchStream = httpClient
                //                        .execute(currentRequest).getEntity()
                //                        .getContent();
                //
                //                  SearchDescription desc = Nucular
                //                        .readOpenSearchFromStream(searchStream);
                //
                //                  if (desc.getSearchLink() != null) {
                //                     searchLink.setHref(desc.getSearchLink().getHref());
                //                     searchLink.setType(AtomConstants.TYPE_ATOM);
                //                  }
                //               } catch (Exception searchIO) {
                //                  LOG.error("Could not get search info", searchIO);
                //               }
            }

            LOG.debug("Using searchURL " + searchLink.getHref());

        }

        return feed;
    } catch (Exception e) {
        this.errorMessage = e.getLocalizedMessage();
        LOG.error("Download failed for url: " + baseUrl, e);
        return null;
    }

}

From source file:com.github.kimikage.uguisuan.WaveReaderService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;/*from   w  w w  .  j  a va 2 s  . c o  m*/
    }
    String filePath = intent.getStringExtra(ARG_FILE_PATH);

    Log.d(TAG, "start");

    Intent bi = new Intent();
    bi.setAction(Receiver.ACTION_PRE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(bi);

    try {
        if (filePath.equals("!")) {
            AssetManager am = getResources().getAssets();
            mStream = new LeDataInputStream(am.open("japanese.wav"));
        } else {
            mStream = new LeDataInputStream(new FileInputStream(filePath));
        }

        readHeader();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    bi.setAction(Receiver.ACTION_UPDATE);

    byte[] buffer = new byte[4];
    int remain = mWave.getRiffSize() - mWave.getFmtSize();
    try {
        while (remain >= 8) {
            mStream.read(buffer);
            int size = mStream.readInt();
            remain -= size + 8;
            if (Arrays.equals(buffer, Wave.CHUNK_ID_DATA)) {
                mWave.setDataSize(size);
                readDataChunk();
            } else {
                mStream.skip(size);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    UguisuAnne app = (UguisuAnne) getApplicationContext();
    app.setSourceWave(mWave);

    bi.setAction(Receiver.ACTION_POST);
    LocalBroadcastManager.getInstance(this).sendBroadcast(bi);
}

From source file:com.acrylicgoat.bcponline.fragments.CPListFragment.java

private CategoryList readJson(String fileName) {
    AssetManager assets = getActivity().getAssets();
    CategoryList catList = new CategoryList();

    Gson gson = new Gson();

    try {/*from w w w  .jav  a2s .  com*/
        InputStream is = assets.open(fileName);
        BufferedReader bf = new BufferedReader(new InputStreamReader(is));
        catList = gson.fromJson(bf, CategoryList.class);
    } catch (IOException ioe) {
        Log.d("json", "Some problem: " + ioe.toString());
    }

    return catList;

}

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  .j  a va  2  s  . co  m*/
            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:de.Maxr1998.xposed.maxlock.ui.ThemeService.java

@SuppressLint("WorldReadableFiles")
public void importTheme(String packageName) {
    /**/*from   w w  w  .  j  av  a 2 s. com*/
     * Preferences
     */
    prefs = getSharedPreferences(Common.PREFS, MODE_PRIVATE);
    /**
     * Files
     */
    AssetManager assets;
    try {
        assets = getPackageManager().getResourcesForApplication(packageName).getAssets();

        // theme.xml file
        InputStream themeStream = assets.open(themeOrigFile);
        FileUtils.copyInputStreamToFile(themeStream, themeFile);
        if (themeFile.length() < 10) {
            Toast.makeText(this, "No theme.xml found, exiting...", Toast.LENGTH_SHORT).show();
            //noinspection ResultOfMethodCallIgnored
            themeFile.delete();
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            getSharedPreferences(Common.PREFS_THEME, MODE_MULTI_PROCESS);
        //noinspection deprecation
        getSharedPreferences(Common.PREFS_THEME, MODE_WORLD_READABLE);

        // background.png
        InputStream backgroundStream = assets.open(backgroundOrigFile);
        File backgroundFile = new File(
                Util.dataDir(this) + File.separator + "theme" + File.separator + backgroundOrigFile);
        FileUtils.copyInputStreamToFile(backgroundStream, backgroundFile);
        if (themeFile.length() < 10)
            //noinspection ResultOfMethodCallIgnored
            backgroundFile.delete();
        else {
            prefs.edit().putString(Common.BACKGROUND, "theme").apply();
        }
    } catch (Exception e) {
        e.printStackTrace();
        clearUp();
    }
}

From source file:com.midisheetmusicmemo.FileUri.java

/** Return the file contents as a byte array.
 *  If any IO error occurs, return null.
 *//*  w  w  w. ja v  a2 s . c o m*/
public byte[] getData(Activity activity) {
    try {
        byte[] data;
        int totallen, len, offset;

        // First, determine the file length
        data = new byte[4096];
        InputStream file;
        String uriString = uri.toString();
        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        totallen = 0;
        len = file.read(data, 0, 4096);
        while (len > 0) {
            totallen += len;
            len = file.read(data, 0, 4096);
        }
        file.close();

        // Now read in the data
        offset = 0;
        data = new byte[totallen];

        if (uriString.startsWith("file:///android_asset/")) {
            AssetManager asset = activity.getResources().getAssets();
            String filepath = uriString.replace("file:///android_asset/", "");
            file = asset.open(filepath);
        } else if (uriString.startsWith("content://")) {
            ContentResolver resolver = activity.getContentResolver();
            file = resolver.openInputStream(uri);
        } else {
            file = new FileInputStream(uri.getPath());
        }
        while (offset < totallen) {
            len = file.read(data, offset, totallen - offset);
            if (len <= 0) {
                throw new MidiFileException("Error reading midi file", offset);
            }
            offset += len;
        }
        file.close();
        return data;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.photon.phresco.hybrid.eshop.activity.PhrescoActivity.java

/**
 * Read phresco-env-config.xml file to get to connect to web service
 *//*from   w ww .j  av a2 s.c o m*/
public void readConfigXML() {
    try {

        Resources resources = getResources();
        AssetManager assetManager = resources.getAssets();

        // Read from the /assets directory
        InputStream inputStream = assetManager.open(Constants.PHRESCO_ENV_CONFIG);

        ConfigReader confReaderObj = new ConfigReader(inputStream);

        PhrescoLogger.info(TAG + "Default ENV = " + confReaderObj.getDefaultEnvName());

        List<Configuration> configByEnv = confReaderObj.getConfigByEnv(confReaderObj.getDefaultEnvName());

        for (Configuration configuration : configByEnv) {
            String envName = configuration.getEnvName();
            String envType = configuration.getType();
            PhrescoLogger.info(TAG + "envName = " + envName + " ----- envType = " + envType);
            //            properties = configuration.getProperties();

            if (envType.equalsIgnoreCase("webservice")) {
                /*String configJsonString = confReaderObj.getConfigAsJSON(envName, WEB_SERVICE, WEBSERVICE_CONFIG_NAME);
                getWebServiceURL(configJsonString);*/
            } else if (envType.equalsIgnoreCase("server")) {
                String configJsonString = confReaderObj.getConfigAsJSON(envName, SERVER, SERVER_CONFIG_NAME);
                getServerURL(configJsonString);
            }

        }

    } catch (ParserConfigurationException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : ParserConfigurationException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (SAXException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : SAXException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (IOException ex) {
        PhrescoLogger.info(TAG + "readConfigXML : IOException: " + ex.toString());
        PhrescoLogger.warning(ex);
    } catch (Exception ex) {
        PhrescoLogger.info(TAG + "readConfigXML : Exception: " + ex.toString());
        PhrescoLogger.warning(ex);
    }
}