Java Code Examples for android.content.res.Resources#openRawResource()

The following examples show how to use android.content.res.Resources#openRawResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainActivity.java    From external-nfc-api with Apache License 2.0 6 votes vote down vote up
public byte[] getResource(int id, Context context) throws IOException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(id);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    byte[] readBuffer = new byte[4 * 1024];

    try {
        int read;
        do {
            read = is.read(readBuffer, 0, readBuffer.length);
            if(read == -1) {
                break;
            }
            bout.write(readBuffer, 0, read);
        } while(true);

        return bout.toByteArray();
    } finally {
        is.close();
    }
}
 
Example 2
Source File: Options.java    From cordova-plugin-firebase-extended-notification with MIT License 6 votes vote down vote up
private Uri getUriForResourcePath(String path) {
    String resPath = path.replaceFirst("res://", "");
    int resId = getResourceIdForDrawable(resPath);
    File file = getTmpFile();
    if (resId == 0)
        return null;
    try {
        Resources res = this.context.getResources();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = res.openRawResource(resId);
        copyFile(inputStream, outStream);
        return getProvidedFileUri(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: InformationDialogPreference.java    From masterpassword with GNU General Public License v3.0 6 votes vote down vote up
public String stringByName(Resources resources, String resourceName) {
    String result = resourceName;
    if (resourceName.length() > 1 && resourceName.charAt(0) == '@' && resourceName.contains("@string/")) {
        result = resources.getString(resources.getIdentifier((new StringBuilder()).append(getContext().getPackageName()).append(":").append(resourceName.substring(1)).toString(), null, null));
    } else if (resourceName.length() > 1 && resourceName.startsWith("raw/")) {
        InputStream contentStream = resources.openRawResource(resources.getIdentifier(resourceName.substring(4), "raw", getContext().getPackageName()));

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        int i;
        try {
            i = contentStream.read();
            while (i != -1) {
                byteArrayOutputStream.write(i);
                i = contentStream.read();
            }
            contentStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        result = byteArrayOutputStream.toString();
    }
    return result;
}
 
Example 4
Source File: MyGLUtils.java    From MusicVisualization with Apache License 2.0 6 votes vote down vote up
private static String getStringFromRaw(Context context, @RawRes int id) {
    String str;
    try {
        Resources r = context.getResources();
        InputStream is = r.openRawResource(id);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = is.read();
        while (i != -1) {
            baos.write(i);
            i = is.read();
        }

        str = baos.toString();
        is.close();
    } catch (IOException e) {
        str = "";
    }

    return str;
}
 
Example 5
Source File: XmlDataLoader.java    From Quiz with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Loads XML with quiz and returns {@link Quiz} object.
 * 
 * @return quiz object
 * @throws Exception
 *             when deserialization fails
 */
public Quiz loadXml() throws Exception {
	Resources resources = context.getResources();
	String languageCode = getLanguageCode(resources);
	// Get XML name using reflection
	Field field = null;
	String prefix = context.getString(R.string.xml_prefix);
	try {
		field = R.raw.class.getField(prefix + languageCode);
	} catch (NoSuchFieldException e) {
		// If there is no language available use default
		field = R.raw.class.getField(prefix + context.getString(R.string.default_language));
	}
	// Create InputSream from XML resource
	InputStream source = resources.openRawResource(field.getInt(null));
	// Parse XML
	Serializer serializer = new Persister();
	return serializer.read(Quiz.class, source);
}
 
Example 6
Source File: ChartParser.java    From currency with GNU General Public License v3.0 6 votes vote down vote up
public boolean startParser(Context context, int id)
{
    // Create the map
    map = new LinkedHashMap<>();

    Resources resources = context.getResources();

    // Read the xml from the resources
    try
    {
        InputStream stream = resources.openRawResource(id);
        Handler handler = new Handler();
        Xml.parse(stream, Xml.Encoding.UTF_8, handler);
        return true;
    }
    catch (Exception e)
    {
        map.clear();
    }

    return false;
}
 
Example 7
Source File: XBitmapUtils.java    From XFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 获取一个指定大小的bitmap
 *
 * @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);
}
 
Example 8
Source File: Parser.java    From currency with GNU General Public License v3.0 6 votes vote down vote up
public boolean startParser(Context context, int id)
{
    // Create the map and add value for Euro
    map = new HashMap<>();
    map.put("EUR", 1.0);

    Resources resources = context.getResources();

    // Read the xml from the resources
    try
    {
        InputStream stream = resources.openRawResource(id);
        Handler handler = new Handler();
        Xml.parse(stream, Xml.Encoding.UTF_8, handler);
        return true;
    }
    catch (Exception e)
    {
        map.clear();
    }

    return false;
}
 
Example 9
Source File: Utils.java    From external-nfc-api with Apache License 2.0 6 votes vote down vote up
public static byte[] getResource(int r, Activity a) throws IOException {
    Resources res = a.getResources();
    InputStream in = res.openRawResource(r);

    byte[] b = new byte[4096];

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    int read;
    do {
        read = in.read(b, 0, b.length);
        if (read == -1) {
            break;
        }
        bout.write(b, 0, read);
    } while (true);

    return bout.toByteArray();
}
 
Example 10
Source File: EMVTerminal.java    From smartcard-reader with GNU General Public License v3.0 6 votes vote down vote up
public static void loadProperties(Resources resources) {
    InputStream defaultStream = resources.openRawResource(R.raw.terminal_properties);
    try {
        defaultTerminalProperties.load(defaultStream);
        for (String key : defaultTerminalProperties.stringPropertyNames()) {
            // sanitize
            String sanitizedKey = Util.byteArrayToHexString(Util.fromHexString(key)).toLowerCase();
            byte[] valueBytes = Util.fromHexString(defaultTerminalProperties.getProperty(key));
            String sanitizedValue = Util.byteArrayToHexString(valueBytes).toLowerCase();
            defaultTerminalProperties.setProperty(sanitizedKey, sanitizedValue);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    ISO3166_1.init(resources);
    ISO4217_Numeric.init(resources);
}
 
Example 11
Source File: UpgradeFirm.java    From Makeblock-App-For-Android with MIT License 6 votes vote down vote up
public int loadFirm()
{
	// load hex file
       Resources res = context.getResources();
       InputStream in_s = res.openRawResource(R.raw.firmware);
       BufferedReader reader = new BufferedReader(new InputStreamReader(in_s));
       try {
		String line = reader.readLine();
		parseHexLine(line);
		while (line != null) {
			line = reader.readLine();
			if(line==null)
				break;
			int ret = parseHexLine(line);
			if(ret>0) hexLen = ret;
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return 0;
}
 
Example 12
Source File: ImageUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("ResourceType")
public static Bitmap loadDefaultAvatar() {
    Resources res = getResources();
    InputStream is = res.openRawResource(R.drawable.default_avatar);
    InputStream is2 = res.openRawResource(R.drawable.default_avatar);
    return loadAvatarFromStream(is, is2);
}
 
Example 13
Source File: AboutActivity.java    From BrainPhaser with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Resource: Pro Android by Syes Y. Hashimi and Satya Komatineni (2009) p.59
 * opens the textfile from credits.txt and reads and converts with convertStreamToString() into a String
 * @return string from .txt file
 * @throws IOException
 */
 String getStringFromRawFile() throws IOException {
    Resources r = getResources();
    InputStream is = r.openRawResource(R.raw.credits);
    String myText = FileUtils.convertStreamToString(is);
    is.close();
    return myText;
}
 
Example 14
Source File: ImageRequestTest.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
private static byte[] readRawResource(Resources res, int resId) throws IOException {
    InputStream in = res.openRawResource(resId);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int count;
    while ((count = in.read(buffer)) != -1) {
        bytes.write(buffer, 0, count);
    }
    in.close();
    return bytes.toByteArray();
}
 
Example 15
Source File: PluginManager.java    From hackerskeyboard with Apache License 2.0 5 votes vote down vote up
@Override
InputStream[] getStreams(Resources res) {
    if (mRawIds == null || mRawIds.length == 0) return null;
    InputStream[] streams = new InputStream[mRawIds.length];
    for (int i = 0; i < mRawIds.length; ++i) {
        streams[i] = res.openRawResource(mRawIds[i]);
    }
    return streams;
}
 
Example 16
Source File: GifView.java    From GifAssistant with Apache License 2.0 5 votes vote down vote up
/**
 * 以资源形式设置gif图片
 * @param resId gif图片的资源ID
 * @param justShowCover 是否只显示第一帧,当该参数为true时,
 *        decoder只解析得到一张图片就为停止工作
 */
public void showGifImage(int resId, boolean justShowCover){
	// 记录gif图片信息,方便debug
	mGifSourceInfos = new GifSourceInfos(GifImageType.GIF_TYPE_FROM_RES);
    mGifSourceInfos.setInfo("resId [" + resId + "]");

    Resources r = this.getResources();
	InputStream is = r.openRawResource(resId);
	showGifDecoderImage(is, justShowCover);
}
 
Example 17
Source File: Licenses.java    From google-authenticator-android with Apache License 2.0 5 votes vote down vote up
private static String getTextFromResource(
    Context context, String filename, long offset, int length) {
  Resources resources = context.getApplicationContext().getResources();
  // When aapt is called with --rename-manifest-package, the package name is changed for the
  // application, but not for the resources. This is to find the package name of a known
  // resource to know what package to lookup the license files in.
  String packageName = resources.getResourcePackageName(R.id.dummy_placeholder);
  InputStream stream =
      resources.openRawResource(resources.getIdentifier(filename, "raw", packageName));
  return getTextFromInputStream(stream, offset, length);
}
 
Example 18
Source File: GifView.java    From GifAssistant with Apache License 2.0 5 votes vote down vote up
/**
 * 以资源形式设置gif图片
 * @param resId gif图片的资源ID

 */
public void showGifImage(int resId){
	// 记录gif图片信息,方便debug
	mGifSourceInfos = new GifSourceInfos(GifImageType.GIF_TYPE_FROM_RES);
    mGifSourceInfos.setInfo("resId [" + resId + "]");
	Resources r = this.getResources();
	InputStream is = r.openRawResource(resId);
	showGifDecoderImage(is, false);
}
 
Example 19
Source File: KeyValueStore.java    From android-anuto with GNU General Public License v2.0 5 votes vote down vote up
public static KeyValueStore fromResources(Resources resources, int resourceId) {
    InputStream stream = resources.openRawResource(resourceId);

    try {
        return fromStream(stream);
    } finally {
        try {
            stream.close();
        } catch (IOException ignored) {
        }
    }
}
 
Example 20
Source File: App.java    From RealmSearchView with Apache License 2.0 4 votes vote down vote up
private void initializeDB() {

        long initTime = System.currentTimeMillis();

        // Realm DB configuration object
        RealmConfiguration config = new RealmConfiguration.Builder(this)
                .name(getResources().getString(R.string.realm_db_filename))
                .schemaVersion(0)
                .build();

        // Clear Realm DB
        Realm.deleteRealm(config);

        Realm realm = Realm.getInstance(config);

        // All writes must be wrapped in a transaction to facilitate safe multi threading
        realm.beginTransaction();

        Map<Class, Integer> JSONres = new HashMap<Class, Integer>();
        JSONres.put(City.class, R.raw.cities);

        Resources res = getResources();

        try {
            for (Map.Entry<Class, Integer> resource : JSONres.entrySet())
            {
                InputStream stream = res.openRawResource(resource.getValue());
                realm.createAllFromJson(resource.getKey(), stream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        // When the transaction is committed, all changes a synced to disk.
        realm.commitTransaction();

        long duration = (System.currentTimeMillis() - initTime);
        long sleepTime = TimeUnit.SECONDS.toMillis(getResources().getInteger(R.integer.splash_max_delay_sec)) - duration;
        Log.d(TAG, "DB insert time: " + duration + "ms");

        if(sleepTime > 0) {
            SystemClock.sleep(sleepTime);
        }

        Log.d(TAG, "Cities in DB: " + realm.where(City.class).findAll().size());

        realm.close();
    }