Home > Tutorials > Store and use files in Assets

Store and use files in Assets


There are times when you probably want to your application distribution with raw resources, instead of pre-defined resources, the ‘res‘ folder, you gonna have to make use of ‘Asset‘.

Assets’ folder will be distributed along with the APK, which contains all the raw files you need for application, such as: text files (.txt), non-Android XML files (.xml), Audio files (.wav, .mp3, .mid)…; those cannot be put into ‘res‘ folder as usual.

Thing needed to be looked up here: AssetManager from Android Developers’ References

This class does the job that we need.

First, create a project as usual, then put files into ‘asset‘ like below:

Files in 'Assets'

Files in 'Assets'

Now, create a simple layout containing a TextView for displaying the content of ‘text.txt‘ and an ImageView for displaying the image ‘avatar.jpg’, which are put in Asset.

The implementation quite easy using AssetManager as mentioned above.

package pete.android.study;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class Main extends Activity {

	ImageView mImage;
	TextView mText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mImage = (ImageView)findViewById(R.id.image);
        mText = (TextView)findViewById(R.id.text);
        loadDataFromAsset();
    }

    public void loadDataFromAsset() {
    	// load text
    	try {
    		// get input stream for text
	    	InputStream is = getAssets().open("text.txt");
	    	// check size
	    	int size = is.available();
	    	// create buffer for IO
	    	byte[] buffer = new byte[size];
	    	// get data to buffer
	    	is.read(buffer);
	    	// close stream
	    	is.close();
	    	// set result to TextView
	    	mText.setText(new String(buffer));
    	}
    	catch (IOException ex) {
    		return;
    	}

    	// load image
    	try {
	    	// get input stream
	    	InputStream ims = getAssets().open("avatar.jpg");
	    	// load image as Drawable
	    	Drawable d = Drawable.createFromStream(ims, null);
	    	// set image to ImageView
	    	mImage.setImageDrawable(d);
    	}
    	catch(IOException ex) {
    		return;
    	}

    }
}

That’s a quick sample code giving this result.

Read data from Asset

Read data from Asset

The distributed APK file contains the folder ‘assets‘, you might wanna check by opening it.

Quite easy, isn’t it?

@p/s: you can load image from Asset into Bitmap by using BitmapFactory.decodeStream(), instead of using Drawable.

Have fun w/ Android Coding 🙂

 

Cheers,

Pete Houston

Categories: Tutorials Tags: , , , , , ,
  1. January 20, 2018 at 9:58 pm

    I’ll post a hyperlink to this webpage on my blog site. I’m certain my guests will locate that extremely handy.

  2. November 9, 2017 at 2:41 pm

    amazing problems entirely, you only acquired a new readers. What would Store and use files in Assets | [ Android Newbie ] anyone advise regarding your publish that you created a week back? Just about any certain?. Poker online http://www.feraripoker.org/

  3. September 6, 2017 at 5:31 am

    My boyfriend introduced me to your articles. Right here is some really useful info. You have a lot of knowledge on this subject. In my view, if all webmasters and bloggers made just right content material as you did, the web might be a lot more helpful than ever before.

  4. September 4, 2017 at 3:30 pm

    I shared this on WordPress. Try to make the guest posts as good as possible by promoting and dropping links. Are there other articles you work on? I am continually browsing online for tips that can help me.

  5. September 3, 2017 at 7:24 am

    I am bored to death at work so I decided to browse your post on my iphone during lunch break. I really like your write up. Your blogs is good!

  6. September 2, 2017 at 1:53 am

    cool post. Interesting post. I really like your posts but… I am super dyslexic. Do you have Youtube videos on the subject?

  7. silpa
    June 17, 2017 at 12:39 pm

    how to take video from assets plz help me

  8. andy rocks
    April 18, 2017 at 1:50 pm

    my imgae in subfolder in assets so what to do?

    i alreasy try.. InputStream ims = getAssets().open(“subfolder/avatar.jpg”);

    but its not working 😦

  9. kapil sharma
    March 19, 2017 at 2:28 pm

    Thank you very much I was really helpful…

  10. faisal
    February 24, 2017 at 3:37 pm

    :

  11. faisal
    February 24, 2017 at 3:35 pm

    how to get asset file path for uploading image in asset folder.

    connection.setRequestProperty(“uploaded_file”,selectedFilePath);
    // connection.setRequestProperty(picture,selectedFilePath);
    AppLog.d(“dooth-prefrences”,”picture params”+ pictureParams);
    //creating new dataoutputstream
    dataOutputStream = new DataOutputStream(connection.getOutputStream());
    //writing bytes to data outputstream
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes(“Content-Disposition: form-data; name=\””+pictureParams+”\”;filename=\””
    + selectedFilePath + “\”” + lineEnd);
    AppLog.d(“dooth-preferences”,”path:”+selectedFilePath+”\””+lineEnd);

  12. January 20, 2017 at 6:21 am

    I think this website holds some really fantastic info for everyone :D. “The test of every religious, political, or educational system is the man that it forms.” by Henri Frdric Amiel.

  13. January 17, 2017 at 7:18 pm

    Thanks for this post this was very helpful!

  14. anonymousers
    September 6, 2016 at 11:20 pm

    how about with multiple image ? thanks

  15. polaris
    August 20, 2016 at 11:30 am

    Works Good !!!
    Thanks

  16. Gaurav Gupta
    June 29, 2016 at 7:12 pm

    how to open pdf file from assets folder…….. plz help……….

  17. January 20, 2016 at 8:17 am

    thanks is very useful for me

  18. Ben
    October 22, 2015 at 4:51 pm

    You should not use the function available()!

    Documentation:
    * the result is a conservative estimate and may be significantly smaller than the actual number of bytes available.*

  19. May 25, 2015 at 6:23 pm

    Reblogged this on Sxx520's Blog and commented:
    see see

  20. November 13, 2014 at 2:59 am

    Reblogged this on weathercode.

  21. varus88
    October 25, 2014 at 9:06 pm

    Большое спасибо, очень помог ваш урок.

  22. October 2, 2014 at 3:32 pm

    Hey man, thanks very much! Assets are nice for many purposes!

  23. MoPo
    August 12, 2014 at 4:59 am

    Thanks a lot. It is 2 days that I’m search internet to find where should I put my test file.
    Thanks a lot.

  24. shawn
    May 16, 2014 at 9:08 pm

    awesome

  25. om
    April 30, 2014 at 9:11 pm

    R.id.text show error

  26. Shafiq Malik
    February 17, 2014 at 4:43 pm

    good work. . . . .

  27. February 10, 2014 at 10:17 am

    how if I want to use it in XML layout instead of from java? thanks

  28. January 31, 2014 at 12:40 pm

    Thankx for sharing your knowledge. Also, i have one question? is that possible to add some images into Assets at Run time and load that images?

  29. January 22, 2014 at 8:40 am

    Hi,can you tell me how should i do if there are two or more folder inside assets?

  30. October 5, 2013 at 2:36 pm

    i want to display images from aasets in the list view…plz tell how it will???

  31. Sunny
    June 30, 2013 at 11:03 am

    Thank you Pete. Simple, very clear example….

  32. Peter Bishop
    January 9, 2013 at 5:22 am

    Hi pete, thank you for the tutorial. I encountered an “out of memory error” when i tried to implement this. The image file I’m trying to display is 23.1kb with dimensions 318×333. I encounter the same error when i try to use BitmapFactory.decode stream. Is there any way around this without having to scale down the image file

  33. mencanbed
    October 13, 2012 at 9:31 pm

    Can you give me the .xml file to display the textview and imageview am a not a Pro

  34. mencanbed
    October 13, 2012 at 9:31 pm

    Can you give me the .xml file to display the textview and imageview am a not a Pro

  35. tumy1
    May 13, 2012 at 12:29 am

    Can you help me?
    Loading files kml from the Raw folders ! How?

  36. zefran
    March 23, 2012 at 7:06 am

    Thank you,
    What directory is talking about.
    Because the menu Window> ShowView> Other … > File Explorer is a directory with the path data / data / application packages would be this external directory?
    I can pull a file from that directory component webview? example: webview.loadUrl (“file :/ / / data / data / pages_web / examples / / index.html”);
    I can create a directory within a file and save it as?

    He understood my question, I just need to know to create directories and write files htmls updated inside.

  37. zefran
    March 19, 2012 at 9:09 am

    how do I write to a file in the Asset and can say the name of the directory and file name? HELP ME

    • March 20, 2012 at 10:41 pm

      Sorry, you can’t do that, directory is where you put all necessary stuffs for your apps and packing the final APK.
      Just make copy of a file in your and write/read to your internal storage in run-time…it’s totally fine.

  1. No trackbacks yet.

Leave a comment