Example usage for android.content.res Resources openRawResource

List of usage examples for android.content.res Resources openRawResource

Introduction

In this page you can find the example usage for android.content.res Resources openRawResource.

Prototype

@NonNull
public InputStream openRawResource(@RawRes int id) throws NotFoundException 

Source Link

Document

Open a data stream for reading a raw resource.

Usage

From source file:com.google.code.twisty.Twisty.java

void startTerp(int resource) {

    String gameName = builtinGames.get(resource); // go-go-autoboxing
    if (gameName == null) {
        Log.i(TAG, "Failed to find built-in game resource" + resource);
        return;/*from  w w w . j av a 2 s  .  c om*/
    }
    Log.i(TAG, "Loading game resource: " + gameName);

    String savedGamesDir = getSavedGamesDir(true);
    if (savedGamesDir == null) {
        showDialog(DIALOG_CANT_SAVE);
        return;
    }

    // The absolute disk path to the privately-stored gamefile:
    File gameFile = new File(savedGamesDir + "/" + gameName);
    String gamePath = gameFile.getAbsolutePath();
    Log.i(TAG, "Looking for gamefile at " + gamePath);

    if (!gameFile.exists()) {
        // Do a one-time dump from raw resource to disk.
        FileOutputStream foutstream;
        Resources r = new Resources(getAssets(), new DisplayMetrics(), null);
        InputStream gamestream = r.openRawResource(resource);
        try {
            foutstream = new FileOutputStream(gameFile);
        } catch (IOException e) {
            Log.i(TAG, "Failed to open outputstream for filename " + gamePath);
            Log.i(TAG, e.getMessage());
            return;
        }
        try {
            Log.i(TAG, "About to spew raw data to disk...");
            suckstream(gamestream, foutstream);
        } catch (IOException e) {
            Log.i(TAG, "Failed to copy raw game to file." + gamePath);
            return;
        }
        Log.i(TAG, "Completed dump of raw data to disk.");
    }

    Log.i(TAG, "Starting gamefile located at " + gamePath);
    startTerp(gamePath);
}

From source file:com.coderstory.FTool.utils.licensesdialog.LicensesDialogFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Resources resources = getResources();

    if (savedInstanceState != null) {
        mTitleText = savedInstanceState.getString(STATE_TITLE_TEXT);
        mLicensesText = savedInstanceState.getString(STATE_LICENSES_TEXT);
        mCloseButtonText = savedInstanceState.getString(STATE_CLOSE_TEXT);
        if (savedInstanceState.containsKey(STATE_THEME_XML_ID)) {
            mThemeResourceId = savedInstanceState.getInt(STATE_THEME_XML_ID);
        }//  w w w  .  ja  v a  2  s. c o m
        if (savedInstanceState.containsKey(STATE_DIVIDER_COLOR)) {
            mDividerColor = savedInstanceState.getInt(STATE_DIVIDER_COLOR);
        }
    } else {
        mTitleText = resources.getString(R.string.notices_title);
        mCloseButtonText = resources.getString(R.string.notices_close);
        try {
            final Notices notices;
            final Bundle arguments = getArguments();
            if (arguments != null) {
                if (arguments.containsKey(ARGUMENT_NOTICES_XML_ID)) {
                    notices = NoticesXmlParser.parse(resources.openRawResource(getNoticesXmlResourceId()));
                } else if (arguments.containsKey(ARGUMENT_NOTICES)) {
                    notices = arguments.getParcelable(ARGUMENT_NOTICES);
                } else {
                    throw new IllegalStateException("Missing ARGUMENT_NOTICES_XML_ID / ARGUMENT_NOTICES");
                }
                if (arguments.getBoolean(ARGUMENT_INCLUDE_OWN_LICENSE, false)) {
                    notices.getNotices().add(LicensesDialog.LICENSES_DIALOG_NOTICE);
                }
                final boolean showFullLicenseText = arguments.getBoolean(ARGUMENT_FULL_LICENSE_TEXT, false);
                if (arguments.containsKey(ARGUMENT_THEME_XML_ID)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        mThemeResourceId = arguments.getInt(ARGUMENT_THEME_XML_ID,
                                android.R.style.Theme_DeviceDefault_Light_Dialog);
                    } else {
                        mThemeResourceId = arguments.getInt(ARGUMENT_THEME_XML_ID);
                    }
                }
                if (arguments.containsKey(ARGUMENT_DIVIDER_COLOR)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        mDividerColor = arguments.getInt(ARGUMENT_DIVIDER_COLOR,
                                android.R.color.holo_blue_light);
                    } else {
                        mDividerColor = arguments.getInt(ARGUMENT_DIVIDER_COLOR);
                    }
                }
                mLicensesText = NoticesHtmlBuilder.create(getActivity()).setNotices(notices)
                        .setShowFullLicenseText(showFullLicenseText).build();
            } else {
                throw new IllegalStateException("Missing arguments");
            }
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:com.yk.notification.util.BitmapUtil.java

/**
 * ??bitmap//from  w  w  w  .  j a v a 2  s .c  o  m
 * 
 * @param res
 *            Resources
 * @param resId
 *            ID
 * @param reqWidth
 *            
 * @param reqHeight
 *            
 */
public static Bitmap getBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
    // BitmapFactory.Options options = new BitmapFactory.Options();
    // options.inJustDecodeBounds = true;
    // BitmapFactory.decodeResource(res, resId, options);
    // options = BitmapHelper.calculateInSampleSize(options, reqWidth,
    // reqHeight);
    // return BitmapFactory.decodeResource(res, resId, options);

    // JNI???
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Config.RGB_565;
    options.inPurgeable = true;
    options.inInputShareable = true;
    InputStream is = res.openRawResource(resId);
    return getBitmapFromStream(is, null, reqWidth, reqHeight);
}

From source file:de.stkl.gbgvertretungsplan.fragments.AboutFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /*/*from www. j  a  va2  s. c o  m*/
            mSpinnerList = new ArrayList<String>();
            mSpinnerList.add(getString(R.string.action_spinner_mainview_today));
            mSpinnerList.add(getString(R.string.action_spinner_mainview_tomorrow));
            mSpinnerAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mSpinnerList);
    */

    View rootView = inflater.inflate(R.layout.fragment_about, container, false).getRootView();

    final Resources res = getResources();
    String[] titles = res.getStringArray(R.array.about_item_titles);
    String[] summaries = res.getStringArray(R.array.about_item_summaries);

    if (titles.length == summaries.length) {
        for (int i = 0; i < titles.length; i++) {
            // format string
            switch (i) {
            // copyright and app information
            case 0:
                try {
                    titles[i] = String.format(titles[i], getString(R.string.app_name), getActivity()
                            .getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            }

            View aboutItem = inflater.inflate(R.layout.item_about, (ViewGroup) rootView, false);
            ((TextView) aboutItem.findViewById(R.id.title)).setText(titles[i]);
            if (!summaries[i].equals(""))
                ((TextView) aboutItem.findViewById(R.id.summary)).setText(summaries[i]);
            else {
                View v = aboutItem.findViewById(R.id.summary);
                ((ViewGroup) v.getParent()).removeView(v);
            }

            // assign onclick handler
            switch (i) {
            // terms of use
            case 1:
                aboutItem.findViewById(R.id.container).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogFragment newFragment = null;
                        newFragment = new PopupDialog(
                                Util.convertStreamToString(res.openRawResource(R.raw.tos)));
                        newFragment.show(getActivity().getSupportFragmentManager(), "tos");
                    }
                });
                break;
            // open source licenses
            case 2:
                aboutItem.findViewById(R.id.container).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogFragment newFragment = null;
                        newFragment = new PopupDialog(
                                Util.convertStreamToString(res.openRawResource(R.raw.licenses)));
                        newFragment.show(getActivity().getSupportFragmentManager(), "license");
                    }
                });
                break;
            }

            ((ViewGroup) rootView).addView(aboutItem);
        }
    }
    return rootView;
}

From source file:me.piebridge.bible.Bible.java

private boolean unpackRaw(Resources resources, boolean newVersion, int resid, File file) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return false;
    }/*from   w w w.j av  a2 s. c o m*/

    if (file.exists()) {
        if (!newVersion) {
            return true;
        }
        file.delete();
    }

    Log.d(TAG, "unpacking " + file.getAbsolutePath());

    try {
        int length;
        byte[] buffer = new byte[8192];
        File tmpfile = new File(file.getAbsolutePath() + ".tmp");
        OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpfile));
        for (int i = 0; i < 20; i++) {
            InputStream is = resources.openRawResource(resid + i);
            while ((length = is.read(buffer)) >= 0) {
                os.write(buffer, 0, length);
            }
            is.close();
        }
        os.close();
        tmpfile.renameTo(file);
    } catch (Exception e) {
        Log.e(TAG, "unpacked " + file.getAbsolutePath(), e);
        return false;
    }

    return true;
}

From source file:com.eveningoutpost.dexdrip.Home.java

private void initializeSearchWords(String jstring) {
    Log.d(TAG, "Initialize Search words");
    wordDataWrapper lcs = new wordDataWrapper();
    try {//from  w w w.j  ava 2  s .  c  o  m

        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.initiallexicon);

        String input = readTextFile(in_s);

        Gson gson = new Gson();
        lcs = gson.fromJson(input, wordDataWrapper.class);

    } catch (Exception e) {
        e.printStackTrace();

        Log.d(TAG, "Got exception during search word load: " + e.toString());
        Toast.makeText(getApplicationContext(), "Problem loading speech lexicon!", Toast.LENGTH_LONG).show();
    }
    Log.d(TAG, "Loaded Words: " + Integer.toString(lcs.entries.size()));
    searchWords = lcs;
}

From source file:cl.gisred.android.InspActivity.java

private void cerrarFormCrear(boolean bSave, View v, int idR) {
    if (bSave) {/*from  w  ww . j  a va  2 s .  c o  m*/
        if (!validarForm(v)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {

            Resources res = getResources();
            InputStream in_s = res.openRawResource(R.raw.index);
            try {
                View vAction = getLayoutValidate(v);
                byte[] b = new byte[in_s.available()];
                in_s.read(b);
                String sHtml = new String(b);
                HtmlUtils oHtml = new HtmlUtils(getApplicationContext(), sHtml);

                String sValueNumMed = "null";

                for (View view : vAction.getTouchables()) {

                    if (view.getClass().getGenericSuperclass().equals(EditText.class)) {
                        EditText oText = (EditText) view;
                        if (!oText.getText().toString().trim().isEmpty()) {
                            String sMapvalue = HtmlUtils.getMapvalue(oText.getId());
                            String sValorChr = oText.getText().toString();
                            oHtml.setValueById(sMapvalue, "txt", sValorChr);
                            if (oText.getId() == R.id.txtOT) {
                                sValueNumMed = sValorChr;
                            }

                            if (sMapvalue != null && sMapvalue.contains("txt_trabajo_cant")) {
                                try {
                                    double dValue = Double.valueOf(sValorChr);
                                    oHtml.sumHH += dValue;
                                } catch (Exception ex) {
                                    Log.e("Double Convert", "error: " + ex.getMessage());
                                }
                            }
                        }
                    } else if (view.getClass().getGenericSuperclass().equals(CheckBox.class)) {
                        CheckBox oCheck = (CheckBox) view;
                        String sCheck = HtmlUtils.getMapvalue(oCheck.getId());
                        sCheck += oCheck.isChecked() ? "si" : "no";
                        oHtml.setValueById(sCheck, "chk", "");
                    } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) {
                        Spinner oSpinner = (Spinner) view;
                        oHtml.setValueById(HtmlUtils.getMapvalue(oSpinner.getId()), "txt",
                                oSpinner.getSelectedItem().toString());
                    } else if (view.getClass().getGenericSuperclass().equals(RadioButton.class)) {
                        RadioButton oRadioButton = (RadioButton) view;
                        if (oRadioButton.isChecked()) {
                            String sRadio = HtmlUtils
                                    .getMapvalue(((RadioGroup) oRadioButton.getParent()).getId());
                            sRadio += oRadioButton.getText().toString().toLowerCase().replace(" ", "");
                            oHtml.setValueById(sRadio, "rad", "");
                        }
                    } else if (view.getClass().getGenericSuperclass().equals(ImageView.class)) {
                    }
                }

                //SUMA TOTAL HH
                oHtml.setValueById("txt_trabajo_cant_tot", "txt", "" + oHtml.sumHH);

                //VALIDAR FIRMAS
                if (valImage(vAction, R.id.imgFirmaIns))
                    oHtml.setValueById("firm_prop", "img", String.format("%s.jpg", R.id.imgFirmaIns));
                if (valImage(vAction, R.id.imgFirmaTec))
                    oHtml.setValueById("firm_tecn", "img", String.format("%s.jpg", R.id.imgFirmaTec));

                if (valImage(vAction, R.id.imgPhoto1))
                    oHtml.setValueById("foto_1", "img", "foto1.jpg");
                if (valImage(vAction, R.id.imgPhoto2))
                    oHtml.setValueById("foto_2", "img", "foto2.jpg");
                if (valImage(vAction, R.id.imgPhoto3))
                    oHtml.setValueById("foto_3", "img", "foto3.jpg");

                oHtml.setTitleHtml(sValueNumMed);

                String sHtmlFinal = oHtml.getHtmlFinal();

                //guardar en disco
                oHtml.createHtml(sHtmlFinal);

                //VIA CustomTabs
                /*String url = oHtml.getPathHtml();
                CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
                CustomTabsIntent customTabsIntent = builder.build();
                customTabsIntent.launchUrl(this, Uri.parse(url));*/

                //VIA CHROME scheme
                if (Util.isPackageExisted("com.android.chrome", this)) {
                    String url = oHtml.getPathHtml();

                    File f = new File(url);

                    MimeTypeMap mime = MimeTypeMap.getSingleton();
                    String ext = f.getName().substring(f.getName().lastIndexOf(".") + 1);
                    String type = mime.getMimeTypeFromExtension(ext);

                    Uri uri = Uri.parse("googlechrome://navigate?url=" + url);

                    Intent in = new Intent(Intent.ACTION_VIEW);
                    //in.setDataAndType(uri, "text/html");

                    in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    in.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                    //Uri uriExternal = FileProvider.getUriForFile(getApplicationContext(), "cl.gisred.android", f);

                    in.setDataAndType(uri, type);

                    //startActivity(in);
                    startActivity(Intent.createChooser(in, "Escoja Chrome"));
                } else {
                    Toast.makeText(this, "Debe instalar Chrome, solo preview disponible", Toast.LENGTH_LONG)
                            .show();
                    Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(oHtml.getPathHtml()));
                    startActivity(myIntent);
                }

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

    menuMultipleActions.setVisibility(View.VISIBLE);
    menuInspeccionActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();
}

From source file:com.zoffcc.applications.zanavi.Navit.java

private boolean extractRes(String resname, String result) {
    int slash = -1;
    boolean needs_update = false;
    File resultfile;/*from w  ww .  j a v a  2 s  .  c om*/
    Resources res = getResources();
    Log.e("Navit", "Res Obj " + res);
    Log.e("Navit", "Res Name " + resname);
    Log.e("Navit", "result " + result);
    int id = res.getIdentifier(resname, "raw", "com.zoffcc.applications.zanavi");
    // int id = res.getIdentifier(resname, "raw", getPackageName());

    Log.e("Navit", "Res ID " + id);

    if (id == 0) {
        return false;
    }

    while ((slash = result.indexOf("/", slash + 1)) != -1) {
        if (slash != 0) {
            Log.e("Navit", "Checking " + result.substring(0, slash));
            resultfile = new File(result.substring(0, slash));
            if (!resultfile.exists()) {
                Log.e("Navit", "Creating dir");
                if (!resultfile.mkdir())
                    return false;
                needs_update = true;
            }
        }
    }

    resultfile = new File(result);

    if (!resultfile.exists()) {
        needs_update = true;
    }

    if (!needs_update) {
        try {
            InputStream resourcestream = res.openRawResource(id);
            FileInputStream resultfilestream = new FileInputStream(resultfile);
            byte[] resourcebuf = new byte[1024];
            byte[] resultbuf = new byte[1024];
            int i = 0;

            while ((i = resourcestream.read(resourcebuf)) != -1) {
                if (resultfilestream.read(resultbuf) != i) {
                    Log.e("Navit", "Result is too short");
                    needs_update = true;
                    break;
                }

                for (int j = 0; j < i; j++) {
                    if (resourcebuf[j] != resultbuf[j]) {
                        Log.e("Navit", "Result is different");
                        needs_update = true;
                        break;
                    }
                }
                if (needs_update)
                    break;
            }

            if (!needs_update && resultfilestream.read(resultbuf) != -1) {
                Log.e("Navit", "Result is too long");
                needs_update = true;
            }

            if (resultfilestream != null) {
                resultfilestream.close();
            }
        } catch (Exception e) {
            Log.e("Navit", "Exception " + e.getMessage());
            return false;
        }
    }

    if (needs_update) {
        Log.e("Navit", "Extracting resource");
        try {
            InputStream resourcestream = res.openRawResource(id);
            FileOutputStream resultfilestream = new FileOutputStream(resultfile);
            byte[] buf = new byte[1024];
            int i = 0;

            while ((i = resourcestream.read(buf)) != -1) {
                resultfilestream.write(buf, 0, i);
            }

            if (resultfilestream != null) {
                resultfilestream.close();
            }
        } catch (Exception e) {
            Log.e("Navit", "Exception " + e.getMessage());
            return false;
        }
    }
    return true;
}