Monday, November 8, 2010

Android #3: Working with Android Assets

Assuming that the user knows to create a HelloWorld kinda simple android app, we will look into understanding assets and means to access them within the android app.

Working with Assets:

Typically the asset folder within any android project that contains static files that one wishes to package within the application for deployment onto the device, read as a stream of bytes and accessed as just like the way we access the file system in java programming language. All files within this folder doesn’t generate an ID in R.java file (auto-generated file).

Following example illustrates accessing contents of a static file from the assets folder in a simple android project:



main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<!-- AssetDemo -->
<TextView android:id="@+id/assetTxtId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textColor="#FFCC33" />

</LinearLayout>
AssetDemoActivity.java:

package in.satworks.android.samples.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;

public class AssetDemoActivity extends Activity {
private TextView assetTxtView=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Retrieving contents of a static file from the assets folder - start
assetTxtView=(TextView)findViewById(R.id.assetTxtId);
readAsset();
// Retrieving contents of a static file from the assets folder - end
}

private void readAsset()
{
//Get asset manager instance
AssetManager assetMngr=getAssets();
//Read contents from file under assets
try {
InputStream inStream=assetMngr.open("HelloAsset.txt");
BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
String assetText="";
String asText="";
while((asText=bReader.readLine())!=null)
{
System.out.println("[AssetDemoActivity] [assetText] ***** "+assetText);
assetText=assetText+asText+"\n";
}
assetTxtView.setText(assetText);
bReader.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

assets/HelloAsset.txt:
AssetDemo: This is referenced from assets/HelloAsset.txt

No comments:

Post a Comment