Understanding Assets

Android provides the assets folder to put files that you want to include with the package. The files in assets folder do not generate an ID in R.java file. You access them in the same way you access files on the file system in any programming language.

The code below is a program that reads the content of a text file (Hello.txt) in the assets folder

The text file has the line “Hello Android”
package mina.android.helloandroid;




import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import android.app.Activity;

import android.content.res.AssetManager;

import android.os.Bundle;

import android.widget.ImageView;

import android.widget.TextView;



public class HelloAndroid extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//Set the Content View

setContentView(R.layout.main);

TextView txtHeader=(TextView)findViewById(R.id.txtHeader);

TextView txtContent=(TextView)findViewById(R.id.txtContent);

//Gets the instance of the asset manager

AssetManager mngr=getAssets();



//Get file names of files in the assets

try

{

String [] files=mngr.list("Files");



txtHeader.setText(txtHeader.getText()+files[0]);


//Read contents of the text file

InputStream is=mngr.open("Files/Hello.txt");

String text=ReadFile(is);

txtContent.setText(text);

}





catch (IOException e) {

txtHeader.setText(e.getMessage());

}

catch (Exception e) {

txtHeader.setText(e.getStackTrace().toString());

}





}

String ReadFile(InputStream is)

{

ByteArrayOutputStream bo=new ByteArrayOutputStream();

byte [] buffer=new byte[1024];

try

{

is.read(buffer);

bo.write(buffer);

bo.close();

is.close();

}

catch(IOException e)

{



}



return bo.toString();

}

}


After running the application it should be like this:

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.