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.example.google.maps.dataviz.MainActivity.java

private void addDataToMap() {
    ArrayList<LatLng> coords = new ArrayList<LatLng>();
    ArrayList<Double> samples = new ArrayList<Double>();
    double minElevation = Integer.MAX_VALUE;
    double maxElevation = Integer.MIN_VALUE;

    try {/*www  .  ja  v a  2 s . c o  m*/
        Resources res = getResources();
        InputStream istream = res.openRawResource(R.raw.elevation);
        byte[] buff = new byte[istream.available()];
        istream.read(buff);
        istream.close();

        String json = new String(buff);
        JSONArray jsonArray = new JSONArray(json);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject sample = jsonArray.getJSONObject(i);

            double elevation = sample.getDouble("elevation");
            minElevation = elevation < minElevation ? elevation : minElevation;
            maxElevation = elevation > maxElevation ? elevation : maxElevation;

            JSONObject location = sample.getJSONObject("location");
            LatLng position = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

            coords.add(position);
            samples.add(elevation);
        }
    } catch (IOException e) {
        Log.e(this.getClass().getName(), "Error accessing elevation data file.");
        return;
    } catch (JSONException e) {
        Log.e(this.getClass().getName(), "Error processing elevation data (JSON).");
        return;
    }

    for (int i = 0; i < coords.size(); i++) {
        double elevation = samples.get(i);
        int height = (int) (elevation / maxElevation * MARKER_HEIGHT);

        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        Bitmap bitmap = Bitmap.createBitmap(MARKER_WIDTH, height, conf);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPaint(mPaint);

        // Invert the bitmap (top red, bottom blue).
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);

        LatLng position = coords.get(i);
        BitmapDescriptor bitmapDesc = BitmapDescriptorFactory.fromBitmap(bitmap);
        mMap.addMarker(new MarkerOptions().position(position).icon(bitmapDesc).alpha(.8f)
                .title(new DecimalFormat("#.## meters").format(elevation)));
    }
}

From source file:fi.aalto.trafficsense.regularroutes.ui.AboutActivity.java

private void loadAndFillField(int resId, TextView field) {
    Resources res = getResources();

    if (res == null || field == null)
        return;/* w  ww  .  jav a 2s . co m*/

    try {

        InputStream stream = res.openRawResource(resId);
        final String fileContent = IOUtil.inputStreamToString(stream, "utf-8");

        field.setText(fileContent);

    } catch (IOException e) {
        field.setText("<load failed>");
    }
}

From source file:com.claude.sharecam.util.CountryMaster.java

private CountryMaster(Context context) {
    mContext = context;// www  .j ava  2s .c  o  m
    Resources res = mContext.getResources();

    // builds country data from json
    InputStream is = res.openRawResource(R.raw.countries);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    JSONArray json = new JSONArray();
    try {
        json = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mCountryList = new String[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject node = json.optJSONObject(i);
        if (node != null) {
            Country country = new Country();
            country.mCountryIso = node.optString("iso");
            country.mDialPrefix = node.optString("tel");
            country.mCountryName = getCountryName(node.optString("iso"));
            mCountries.add(country);
            mCountryList[i] = country.mCountryIso;
        }
    }
}

From source file:io.hypertrack.sendeta.model.CountryMaster.java

private CountryMaster(Context context) {
    mContext = context;//  w w  w. j  a  v a2  s  . co  m
    Resources res = mContext.getResources();

    // builds country data from json
    InputStream is = res.openRawResource(R.raw.countries);
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String jsonString = writer.toString();
    JSONArray json = new JSONArray();
    try {
        json = new JSONArray(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mCountryList = new String[json.length()];
    for (int i = 0; i < json.length(); i++) {
        JSONObject node = json.optJSONObject(i);
        if (node != null) {
            Country country = new Country();
            country.mCountryIso = node.optString("iso");
            country.mDialPrefix = node.optString("tel");
            country.mCountryName = getCountryName(node.optString("iso"));
            country.mImageId = getCountryFlagImageResource(node.optString("iso"));

            mCountries.add(country);
            mCountryList[i] = country.mCountryIso;
        }
    }
}

From source file:org.akvo.flow.service.SurveyDownloadService.java

private Survey loadSurvey(Survey survey) {
    InputStream in = null;// ww w. java 2  s  .c  o m
    Survey hydratedDurvey = null;
    try {
        if (ConstantUtil.RESOURCE_LOCATION.equalsIgnoreCase(survey.getLocation())) {
            // load from resource
            Resources res = getResources();
            in = res.openRawResource(res.getIdentifier(survey.getFileName(), ConstantUtil.RAW_RESOURCE,
                    ConstantUtil.RESOURCE_PACKAGE));
        } else {
            // load from file
            File f = new File(FileUtil.getFilesDir(FileType.FORMS), survey.getFileName());
            in = new FileInputStream(f);
        }
        hydratedDurvey = SurveyDao.loadSurvey(survey, in);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "Could not parse survey survey file", e);
        PersistentUncaughtExceptionHandler.recordException(e);
    } finally {
        FileUtil.close(in);
    }
    return hydratedDurvey;
}

From source file:com.idevity.card.read.ShowCard.java

/**
 * Method onCreateView./*w  w w  . j ava  2s .c  om*/
 * 
 * @param inflater
 *            LayoutInflater
 * @param container
 *            ViewGroup
 * @param savedInstanceState
 *            Bundle
 * @return View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Globals g = Globals.getInstance();
    View cardLayout = inflater.inflate(R.layout.activity_show_card, container, false);

    Date now = Calendar.getInstance().getTime();

    byte[] _data = g.getCard();
    CardData80073 carddata = new CardData80073(_data);

    PIVCardHolderUniqueID chuid = null;
    PIVDataTempl chuidInDataTempl = carddata.getPIVCardHolderUniqueID();
    if (chuidInDataTempl != null) {
        byte[] chuidData = chuidInDataTempl.getData();
        if (chuidData == null) {
            chuidData = chuidInDataTempl.getEncoded();
        }
        chuid = new PIVCardHolderUniqueID(chuidData);
    }
    FASCN fascn = null;
    try {
        fascn = chuid.getFASCN();
    } catch (Throwable e) {
        Log.e(TAG, "Error: " + e.getMessage());
    }

    String ac = new String();
    String sc = new String();
    String cn = new String();
    String pi = new String();
    String oc = new String();
    String oi = new String();
    String poa = new String();
    String expiryDate = new String();
    String guid = new String();
    String agencyname = new String();
    String orgname = new String();
    Date expires = now;

    if (fascn != null) {
        ac = fascn.getAgencyCode();
        sc = fascn.getSystemCode();
        cn = fascn.getCredentialNumber();
        pi = fascn.getPersonIdentifier();
        oc = fascn.getOrganizationalCategory();
        oi = fascn.getOrganizationalIdentifier();
        poa = fascn.getAssociationCategory();
        expiryDate = chuid.getExpirationDate().toString();
        expires = chuid.getExpirationDate();
        guid = chuid.getGUID().toString();
        // agencyname
        // orgname
    }

    ImageView sigthumbs = (ImageView) cardLayout.findViewById(R.id.validityIndicator1);
    TextView sigtext = (TextView) cardLayout.findViewById(R.id.validityLabel);
    TextView vtText = (TextView) cardLayout.findViewById(R.id.expirydateLabel);

    if (expires.after(now)) {
        sigthumbs.setImageResource(R.drawable.cert_good);
    } else {
        sigthumbs.setImageResource(R.drawable.cert_bad);
        sigtext.setTextColor(getResources().getColor(R.color.idredmain));
        vtText.setTextColor(getResources().getColor(R.color.idredmain));
    }

    // set agency code default
    TextView editAgencyCode = (TextView) cardLayout.findViewById(R.id.agencyCode);
    editAgencyCode.setText(ac);
    // set system code default
    TextView editSystemCode = (TextView) cardLayout.findViewById(R.id.systemCode);
    editSystemCode.setText(sc);
    // set credential number default
    TextView editCredNumber = (TextView) cardLayout.findViewById(R.id.credNumber);
    editCredNumber.setText(cn);
    // set pi number default
    TextView editPersonId = (TextView) cardLayout.findViewById(R.id.personId);
    editPersonId.setText(pi);
    // set org category
    String organizationalCategory = oc;
    if (organizationalCategory.equalsIgnoreCase("1")) {
        oc = "Federal";
    } else if (organizationalCategory.equalsIgnoreCase("2")) {
        oc = "State";
    } else if (organizationalCategory.equalsIgnoreCase("3")) {
        oc = "Commercial";
    } else if (organizationalCategory.equalsIgnoreCase("4")) {
        oc = "International";
    } else {
        // Default is "Federal"
        oc = "Federal";
    }
    TextView editOrgCat = (TextView) cardLayout.findViewById(R.id.orgCategory);
    editOrgCat.setText(oc);
    // set poa code
    String associationCategory = poa;
    if (associationCategory.equalsIgnoreCase("1")) {
        poa = "Employee";
    } else if (associationCategory.equalsIgnoreCase("2")) {
        poa = "Civil";
    } else if (associationCategory.equalsIgnoreCase("3")) {
        poa = "Executive";
    } else if (associationCategory.equalsIgnoreCase("4")) {
        poa = "Uniformed";
    } else if (associationCategory.equalsIgnoreCase("5")) {
        poa = "Contractor";
    } else if (associationCategory.equalsIgnoreCase("6")) {
        poa = "Affiliate";
    } else if (associationCategory.equalsIgnoreCase("7")) {
        poa = "Beneficiary";
    } else {
        // Default is "Employee"
        poa = "None Specified";
    }
    TextView editPoaCode = (TextView) cardLayout.findViewById(R.id.poaCode);
    editPoaCode.setText(poa);
    // set ord id
    TextView editOrgid = (TextView) cardLayout.findViewById(R.id.orgId);
    editOrgid.setText(oi);
    // set expiry date
    TextView editExpiry = (TextView) cardLayout.findViewById(R.id.expiryDate);
    editExpiry.setText(expiryDate);
    // set guid
    TextView editGuid = (TextView) cardLayout.findViewById(R.id.globadId);
    editGuid.setText(guid);

    Resources res = getResources();
    InputStream is = res.openRawResource(R.raw.sp80087);
    Properties codes = new Properties();
    try {
        codes.loadFromXML(is);
    } catch (InvalidPropertiesFormatException e) {
        Log.e(TAG, "Error: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "Error: " + e.getMessage());
    }

    if (codes.getProperty(ac) == null) {
        agencyname = "Unknown Agency";
    } else {
        agencyname = codes.getProperty(ac);
    }
    /*
     * set issuing agency from XML data
     */
    TextView editAgencyname = (TextView) cardLayout.findViewById(R.id.issuingAgency);
    editAgencyname.setText(agencyname);

    if (codes.getProperty(oi) == null) {
        orgname = "Unknown Organization";
    } else {
        orgname = codes.getProperty(oi);
    }
    /*
     * set organization name from XML data
     */
    TextView editOrgname = (TextView) cardLayout.findViewById(R.id.issuingOrg);
    editOrgname.setText(orgname);

    return cardLayout;
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 * The URI for a resource./*from  ww  w .ja  va2  s .  c o m*/
 * 
 * @param path
 *            The given relative path
 * 
 * @return The URI pointing to the given path
 */
private Uri getUriForResourcePath(String path) {
    String resPath = path.replaceFirst("res://", "");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    String resName = fileName.substring(0, fileName.lastIndexOf('.'));
    String extension = resPath.substring(resPath.lastIndexOf('.'));
    File dir = activity.getExternalCacheDir();
    if (dir == null) {
        Log.e("Asset", "Missing external cache dir");
        return Uri.EMPTY;
    }
    String storage = dir.toString() + STORAGE_FOLDER;
    int resId = getResId(resPath);
    File file = new File(storage, resName + extension);
    if (resId == 0) {
        Log.e("Asset", "File not found: " + resPath);
        return Uri.EMPTY;
    }
    new File(storage).mkdir();
    try {
        Resources res = activity.getResources();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = res.openRawResource(resId);
        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.cem.echo.Echo.java

protected boolean getCertificateList(CallbackContext callbackContext) {
    System.out.println("-----getcertlist: entrance deneme");

    List<String> certs = new ArrayList<String>();

    try {/*from w w w. ja v a  2 s.c  o  m*/
        /*            InputStream lisansStream = cordova.getActivity().getResources().openRawResource(cordova.getActivity().getResources().getIdentifier("lisans", "raw", cordova.getActivity().getPackageName()));
                    LicenseUtil.setLicenseXml(lisansStream);
                    lisansStream.close();*/

        Resources activityRes = cordova.getActivity().getResources();
        int lisansid = activityRes.getIdentifier("lisans", "raw", cordova.getActivity().getPackageName());
        InputStream lisansStream = activityRes.openRawResource(lisansid);
        LicenseUtil.setLicenseXml(lisansStream);
        lisansStream.close();

        System.out.println("-----getcertlist: lisans aldik");

        mTerminalHandler = new SCDTerminalHandler(cordova.getActivity());

        mAPDUSmartCard = new APDUSmartCard(mTerminalHandler);
        mAPDUSmartCard.setDisableSecureMessaging(true);

        CardTerminal[] terminalList = mAPDUSmartCard.getTerminalList();

        CardTerminal cardTerminal = terminalList[0];

        //System.out.println("hehehe " + terminalList[0]);

        mAPDUSmartCard.openSession(cardTerminal);
        String readerName = cardTerminal.getName();
        List<byte[]> signCertValueList = mAPDUSmartCard.getSignatureCertificates();

        certificateList = new ArrayList<ECertificate>();

        for (byte[] signCertValue : signCertValueList) {
            ECertificate signCert = new ECertificate(signCertValue);
            //Sadece nitelikli sertifikalar ekiliyor.
            //Kanuni geerlilii olmayan sertifikalarla imza atlmak istenirse bu kontrol kaldrlabilir.
            //  if(signCert.isQualifiedCertificate()){
            certificateList.add(signCert);
            System.out.println("Sertifika Sahibi :" + signCert.getSubject().getCommonNameAttribute());
            certs.add(signCert.getSubject().getCommonNameAttribute());
            //}
        }
    } catch (Exception e) {
        e.printStackTrace();
        PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        //callbackContext.error("Sertifikalar alrken bir hata olutu.");
        return false;
    }

    String[] res = new String[certs.size()];
    certs.toArray(res);

    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, new JSONArray(certs));
    pluginResult.setKeepCallback(true);
    callbackContext.sendPluginResult(pluginResult);
    //callbackContext.success(new JSONArray(certs));
    return true;
}

From source file:edu.cmu.cs.diamond.android.Filter.java

public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException {
    Resources r = context.getResources();
    String resourceName = r.getResourceEntryName(resourceId);
    File f = context.getFileStreamPath(resourceName);

    if (!f.exists()) {
        InputStream ins = r.openRawResource(resourceId);
        byte[] buf = IOUtils.toByteArray(ins);
        FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE);
        IOUtils.write(buf, fos);/*w  w w. j a  va  2  s .  c  o m*/
        context.getFileStreamPath(resourceName).setExecutable(true);
        fos.close();
    }

    ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath());
    Map<String, String> env = pb.environment();
    tempDir = File.createTempFile("filter", null, context.getCacheDir());
    tempDir.delete(); // Delete file and create directory.
    if (!tempDir.mkdir()) {
        throw new IOException("Unable to create temporary directory.");
    }
    env.put("TEMP", tempDir.getAbsolutePath());
    env.put("TMPDIR", tempDir.getAbsolutePath());
    proc = pb.start();
    is = proc.getInputStream();
    os = proc.getOutputStream();

    sendInt(1);
    sendString(name);
    sendStringArray(args);
    sendBinary(blob);

    while (this.getNextToken().tag != TagEnum.INIT)
        ;
    Log.d(TAG, "Filter initialized.");
}

From source file:de.appplant.cordova.plugin.emailcomposer.EmailComposer.java

/**
 * The URI for a resource./* w w w.  j  a  va 2 s  . co m*/
 *
 * @param {String} path
 *      The given relative path
 *
 * @return The URI pointing to the given path
 */
private Uri getUriForResourcePath(String path) {
    String resPath = path.replaceFirst("res://", "");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    String resName = fileName.substring(0, fileName.lastIndexOf('.'));
    String extension = resPath.substring(resPath.lastIndexOf('.'));
    String storage = cordova.getActivity().getExternalCacheDir().toString() + STORAGE_FOLDER;

    int resId = getResId(resPath);
    File file = new File(storage, resName + extension);

    if (resId == 0) {
        System.err.println("Attachment resource not found: " + resPath);
    }

    new File(storage).mkdir();

    try {
        Resources res = cordova.getActivity().getResources();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = res.openRawResource(resId);

        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Uri.fromFile(file);
}