[android] How to get access to raw resources that I put in res folder?

In J2ME, I've do this like that: getClass().getResourceAsStream("/raw_resources.dat");

But in android, I always get null on this, why?

This question is related to android java-me resources inputstream android-resources

The answer is


InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.


TextView txtvw = (TextView)findViewById(R.id.TextView01);
        txtvw.setText(readTxt());

 private String readTxt()
    {
    InputStream raw = getResources().openRawResource(R.raw.hello);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int i;
    try
    {
        i = raw.read();
        while (i != -1)
        {
            byteArrayOutputStream.write(i);
            i = raw.read();
        }
        raw.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block

        e.printStackTrace();
    }


    return byteArrayOutputStream.toString();

}

TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)

Ist 2 lines are 2 written in onCreate() method

rest is to be written in class extending Activity!!


An advance approach is using Kotlin Extension function

fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
    return resources.openRawResource(resourceId)
}

One more interesting thing is extension function use that is defined in Closeable scope

For example you can work with input stream in elegant way without handling Exceptions and memory managing

fun Context.readRaw(@RawRes resourceId: Int): String {
    return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}

This worked for for me: getResources().openRawResource(R.raw.certificate)


In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);

For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName) from your activity.


getClass().getResourcesAsStream() works fine on Android. Just make sure the file you are trying to open is correctly embedded in your APK (open the APK as ZIP).

Normally on Android you put such files in the assets directory. So if you put the raw_resources.dat in the assets subdirectory of your project, it will end up in the assets directory in the APK and you can use:

getClass().getResourcesAsStream("/assets/raw_resources.dat");

It is also possible to customize the build process so that the file doesn't land in the assets directory in the APK.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to java-me

Extract source code from .jar file Difference between volatile and synchronized in Java Difference between Java SE/EE/ME? How to get access to raw resources that I put in res folder? J2ME/Android/BlackBerry - driving directions, route between two locations Convert a JSON string to object in Java ME? How Long Does it Take to Learn Java for a Complete Newbie? How do I convert between ISO-8859-1 and UTF-8 in Java?

Examples related to resources

Spring Boot access static resources missing scr/main/resources How do I add a resources folder to my Java project in Eclipse Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Reading a resource file from within jar How to fix the "508 Resource Limit is reached" error in WordPress? How to get absolute path to file in /resources folder of your project getResourceAsStream returns null How to read file from res/raw by name Load image from resources Resource leak: 'in' is never closed

Examples related to inputstream

Convert InputStream to JSONObject How to read all of Inputstream in Server Socket JAVA Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? How to create streams from string in Node.Js? How can I read a text file in Android? Can you explain the HttpURLConnection connection process? Open URL in Java to get the content How to convert byte[] to InputStream? Read input stream twice AmazonS3 putObject with InputStream length example

Examples related to android-resources

Failed linking file resources Execution failed for task ':app:processDebugResources' even with latest build tools getResources().getColor() is deprecated getColor(int id) deprecated on Android 6.0 Marshmallow (API 23) Android getResources().getDrawable() deprecated API 22 Android Studio cannot resolve R in imported project? Android XXHDPI resources Android ImageView setImageResource in code format statement in a string resource file Lint: How to ignore "<key> is not translated in <language>" errors?