Pages

Thursday, April 12, 2012

Read Text From the Raw Content in Resource Folder.

You can store the raw content in the raw folder and read using the below method..
1. Create a file in and Raw content
2. Create Method called readTextResource() in the util class
3. Use the below code to read the data
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
4. Return the StringBuffer value.
5. If you need a html format, you can use the html util class
Html.fromHtml(text); - It returns Spanned instance.

Sample Code
-----------
public class MainActivity extends Activity {

private Spanned mText = null;
private TextView mTextView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.sampleText);
if (mText == null) {
String text = readTextResource(R.raw.license, this);
mText = Html.fromHtml(text);
}
mTextView.setText(mText);
}
public String readTextResource(int resourceId, Activity owner) {
StringBuffer strBuffer = new StringBuffer();
InputStream inputStream = null;
try {
inputStream = owner.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String str = br.readLine();
while (str != null) {
strBuffer.append(str);
str = br.readLine();
}
} catch (IOException e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
return strBuffer.toString();
}
}