Wednesday, November 16, 2011

Hide showed Toast Messages

In my App, there is a list, when a user clicks on an button, a toast message is being displayed, 10 items - 10 toast messages, so if the user clicks 10 times, then presses the button... he/she has to wait for some seconds, until he's able to read the menu option text.

I have found the below solution to hide the shows toast message.

public class SampleToastActivity extends Activity {
Toast myToast;
static int i=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
if(myToast!=null){
myToast.cancel();
myToast.setText("Count"+i);
}else{
myToast = Toast.makeText(SampleToastActivity.this, "Sample"+i, 10);
}
myToast.show();
}
});
}
}

Monday, November 7, 2011

Sample CheckedTextView in listview , Reading contacts all emails

Here, you can find the example of checked textview in the listview and read all email address in the android phone

1. Design the main Layout & row Layout with Checked TextView
Main.xml
< ListView android:id="@+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#ffffff" />

Row.xml

< CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/checkedTextView1" android:paddingLeft="20dip"
android:paddingRight="20dip" android:paddingTop="10dip"
android:paddingBottom="10dip" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical" android:checkMark="@android:drawable/checkbox_off_background"
android:textColor="#000000" />

2. Create the CursurAdpater

private class ContactListAdapter extends CursorAdapter {

public ContactListAdapter(Context context, Cursor c) {
super(context, c);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
String o = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
CheckedTextView tt = (CheckedTextView) view
.findViewById(R.id.checkedTextView1);
tt.setText(o);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v;
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
return v;
}
}

3. set the Contact Cursor to the ContactListAdapter
ContentResolver cr = getContentResolver();
Cursor emails = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null,
null, null);
l.setAdapter(new ContactListAdapter(this, emails));



4. Change the State while select the Item
l.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView arg0, View v, int arg2,
long arg3) {

CheckedTextView tt = (CheckedTextView) v
.findViewById(R.id.checkedTextView1);
if (!tt.isChecked()) {
tt.setChecked(true);
tt.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
} else {
tt.setChecked(false);
tt.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
}

}
});

5. Add the Contact Read Permission in androidmanifest.xml
< uses-permission android:name="android.permission.READ_CONTACTS" />


Sample Program :

public class ContactListingActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView l = (ListView) findViewById(R.id.listView1);
Cursor emails = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null,
null, null);
l.setAdapter(new ContactListAdapter(this, emails));
l.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View v, int arg2,
long arg3) {
CheckedTextView tt = (CheckedTextView) v
.findViewById(R.id.checkedTextView1);
if (!tt.isChecked()) {
tt.setChecked(true);
tt.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
} else {
tt.setChecked(false);
tt.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
}

}
});

}

private class ContactListAdapter extends CursorAdapter {
public ContactListAdapter(Context context, Cursor c) {
super(context, c);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
String o = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
CheckedTextView tt = (CheckedTextView) view
.findViewById(R.id.checkedTextView1);
tt.setText(o);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v;
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
return v;
}
}
}



Friday, August 12, 2011

Gesture based action

Here we are discussing about how to set that as the gesture listener for the views that I add.
My requirement : I have list of images in a listview with url. When the user wants view the full image then user click the image on the list view
it will take to me the anonther activity and open in a imageview. and as a user wants to tee the next nexe or previous image with come back to listview page

Solution : I have created the HashMap Contains the list of images and pass the selected images name as bundle string. In a detail view created the async task the fetch image from the internet
implement the gestureListener. In this article we discussing about that

Related : gesture move action, gesture based action, example geatures

1. Create a Activity implements OnClickListener
public class MySample1Activity extends Activity implements OnClickListener {
........
}
2. Initialize below required object for gestureListener
ViewConfiguration vc;

static int SWIPE_MAX_OFF_PATH = 250;
static int SWIPE_MIN_DISTANCE = 100;
static int SWIPE_THRESHOLD_VELOCITY = 100;

private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

3. Set Densitybased velocity
vc = ViewConfiguration.get(this);
SWIPE_MIN_DISTANCE = vc.getScaledTouchSlop();
SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();

4. Create a Custom GestureListener class which extends SimpleOnGestureListener
class MyGestureDetector extends SimpleOnGestureListener {

}

5. Override the onFling() and implement the geature move action
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Left Swipe",
Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Right Swipe",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}

Full SourceCode
public class MySample1Activity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
TextView tView;

ViewConfiguration vc;

static int SWIPE_MAX_OFF_PATH = 250;
static int SWIPE_MIN_DISTANCE = 100;
static int SWIPE_THRESHOLD_VELOCITY = 100;

private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tView = (TextView) findViewById(R.id.textview1);
vc = ViewConfiguration.get(this);
SWIPE_MIN_DISTANCE = vc.getScaledTouchSlop();
SWIPE_THRESHOLD_VELOCITY = vc.getScaledMinimumFlingVelocity();

gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
tView.setOnClickListener(this);
tView.setOnTouchListener(gestureListener);
}

class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Left Swipe",
Toast.LENGTH_SHORT).show();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(MySample1Activity.this, "Right Swipe",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// nothing
}
return false;
}
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

}

}

Friday, July 29, 2011

In this blog we are selecting multiple images.Here I have created the custom view components and activity used to get the selected images.

1. Custom ViewComponet

< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
< ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" />
< CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
< /RelativeLayout>

2. SampleActivity

1. Create a ImageAdapter
public class ImageAdapter extends BaseAdapter {
}

2. Inflate the View
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.mygallert, null);
3. find the required View
imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

4. Control the image selection
imageview.setBackgroundResource(R.drawable.icon);
checkbox.setId(position);
checkbox.setChecked(false);
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
cb.setChecked(true);
selectedImage.add(v.getId());
} else {
cb.setChecked(false);
selectedImage.remove(v.getId());
}
}
});

4. Track the image selection
selectedImage.add(v.getId());
selectedImage.remove(v.getId());

5. displays the selected Image Position
Toast.makeText(SampleActivity.this,"" + SampleActivity.this.selectedImage, 10).show();

Sample

public class SampleActivity extends Activity {
private ImageAdapter imageAdapter;
private Set selectedImage = new HashSet();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
Button selectedImage = (Button) findViewById(R.id.selectBtn);
imageAdapter = new ImageAdapter();
imagegrid.setAdapter(imageAdapter);
selectedImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(SampleActivity.this,
"" + SampleActivity.this.selectedImage, 10).show();

}
});

}

public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;

public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview;
CheckBox checkbox;
convertView = mInflater.inflate(R.layout.mygallert, null);
imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
imageview.setBackgroundResource(R.drawable.icon);
checkbox.setId(position);
checkbox.setChecked(false);
checkbox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
cb.setChecked(true);
selectedImage.add(v.getId());
} else {
cb.setChecked(false);
selectedImage.remove(v.getId());
}
}
});
return convertView;
}

public int getCount() {
return 5;
}
}

}

Required XML
main.xml
< ?xml version="1.0" encoding="utf-8"?>
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
< Button android:id="@+id/selectBtn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Select"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" android:minWidth="200px" />
< GridView android:id="@+id/PhoneImageGrid"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center"
android:layout_above="@id/selectBtn" />
< /RelativeLayout>

mygallery.xml
< ?xml version="1.0" encoding="utf-8"?>
< RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
< ImageView android:id="@+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" />
< CheckBox android:id="@+id/itemCheckBox" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
< /RelativeLayout>

Monday, May 23, 2011

Android Shell Commands

Here you can find the available command set in the shell by typing this at the android shell prompt:

dumpcrash, am, dumpstate, input, itr, monkey, pm, svc, ssltest,
debuggerd, dhcpcd, hostapd_cli, fillup, linker, logwrapper, telnetd, iftop, mkdosfs, mount,
mv, notify, netstat, printenv, reboot, ps, renice, rm, rmdir,rmmod, sendevent, schedtop,
ping, sh, hciattach, sdptool, logcat, servicemanager, dbus-daemon, debug_tool, flash_image, installd,
dvz, hostapd, htclogkernel, mountd, qemud, radiooptions, toolbox, hcid,
route, setprop, sleep, setconsole, smd, stop, top, start, umount,
vmstat, wipe, watchprops, sync, netcfg, Chmod, date, dd, cmp, cat, dmesg, df,
getevent, getprop, hd, id, ifconfig, insmod, ioctl, kill,
ln, log, lsmod, ls, mkdir, dumpsys, service, playmp3, sdutil,
rild, dalvikvm, dexopt, surfaceflinger, app_process, mediaserver, system_server,

Sunday, May 22, 2011

Combine two images in android java


In this blog we are combine two images and we have two images stored locally on an SD card or drawble folder in android.

Steps:

Read the image from Source
InputStream istream = context.getResources().openRawResource(R.drawable.img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(R.drawable.img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}

Define the Image property
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}

Create your target Bitmap,
Bitmap combinedImages = Bitmap.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);

Create a Canvas for it,
Canvas comboImage = new Canvas(combinedImages);
Use Canvas.drawBitmap to blit each source bitmap into your target bitmap
comboImage.drawBitmap(image1, 0f, 0f, null);
comboImage.drawBitmap(image2, 0f, image1.getHeight()+1, null);

Example:
public Bitmap combineImages(Context context, int img1, int img2) {
// Bitmap[] mBitmap = new Bitmap[6];
Bitmap image1, image2;

InputStream istream = context.getResources().openRawResource(img1);
try {
image1 = BitmapFactory.decodeStream(istream);
istream = context.getResources().openRawResource(img2);
image2 = BitmapFactory.decodeStream(istream);
} finally {
try {
istream.close();
} catch (IOException e) {
}
}
int width = 0, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Bitmap combinedImages = null;
combinedImages = Bitmap
.createBitmap(width * 2, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(combinedImages);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight()+1, null);
return cs;
}

Sunday, May 15, 2011

Scrollable Text View in andriod -2


This article helps to making Scrollable TextView using TextView with dispatchKeyEvent

we can make a scrollable textview while implement the setMovementMethod and dispatchKeyEvent.

1. private TextView mTextView;

2. Set the Required data in the TextView
mTextView = (TextView) findViewById(R.id.textView1);
mTextView.setText("this is for testing \nthis is for testing \nthis is for testing
\nthis is for testing \nthis is for testing \nthis is for testing \n");

3. mTextView.setMovementMethod(new ScrollingMovementMethod(){.....})

4. Override the methods in ScrollingMovementMethod

new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {}
@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}

private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
}


5. Call the dispatch method in your code
mTextView.dispatchKeyEvent(event);


SAMPLE

public class MainActivity extends Activity {
/** Called when the activity is first created. */

private TextView mTextView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView1);
mTextView
.setText("this is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \nthis is for testing \n");

mTextView.setMovementMethod(new ScrollingMovementMethod() {
public void onTakeFocus(TextView widget, Spannable text, int dir) {

}

@Override
public boolean onKeyDown(TextView widget, Spannable buffer,
int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
down(widget, buffer);
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
for (int i = 0, scrollAmount = getScrollAmount(widget); i < scrollAmount; i++) {
up(widget, buffer);
}
return true;
default:
return super.onKeyDown(widget, buffer, keyCode, event);
}
}
private int getScrollAmount(TextView widget) {
final int visibleLineCount = (int) ((1f * widget.getHeight()) / widget
.getLineHeight());
int scrollAmount = visibleLineCount - 1;
if (scrollAmount < 1) {
scrollAmount = 1;
}
return scrollAmount;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:

return true;
case KeyEvent.KEYCODE_DPAD_UP:
mTextView.dispatchKeyEvent(event);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
}

Scrollable Text View in andriod


This article helps to making Scrollable TextView in Android.

We can do it two ways. 1.Create a TextView inside the ScrollView and 2. TextView with dispatch Events.


Create a TextView inside the ScrollView
< ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:fillViewport="true">
< LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent">
< TextView android:text="@+id/TextView01"
android:id="@+id/mTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">< / TextView>

< / LinearLayout>
< / ScrollView>

Activity Implementation
mTextView = (TextView) findViewById(R.id.logTextView);
mTextView .setText("");
mTextView .setMovementMethod(ScrollingMovementMethod.getInstance());

Thursday, May 12, 2011

How to Obfuscated Android Code

Obfuscated code is source or machine code that has been made difficult to understand for humans. Programmers may deliberately obfuscate code to conceal its purpose or its logic to prevent tampering, deter reverse engineering, or as a puzzle or recreational challenge for someone reading the source code.
Programs known as obfuscators transform readable code into obfuscated code using various techniques. Code obfuscation is different in essence from hardware obfuscation, where description and/or structure of a circuit is modified to hide its functionality.


The following steps to describe the android obfuscation


1) Setup the obfuscated environment Download the follwing file before you starts

ProGuard

ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition.

Download From Sourceforge : http://sourceforge.net/projects/proguard/files/

Reference : http://proguard.sourceforge.net/


Download files from internet

  • add-proguard-release.xml
  • procfg.txt

1) To update an existing Android project, open a command-line and navigate to the tools/ directory of your SDK. Now run:

android update project --name --target --path

2) So, now you have a signed build from the command line, but still no obfuscated build.

To make things easy, you’re going to want to get two helper files:


add-proguard-release.xml and procfg.txt

Copy these files into your root directory (where the build.xml file found).

3) To add Proguard to your build, you first need to edit your local properties file to add the location of the directory that Proguard is installed in:


proguard.dir=/Directory/Proguard/Is/Installed/In

3) Finally... you need to add our script to your build file and have it override a few targets. To do this, we use the XML “entity” construct. At the top of your build.xml file, add an entity that references our script file:

]

>

4) By default ADT creates a proguard.cfg file with every new project, so if you have an existing project just copy it over from a new dummy project. The next step is to enable ProGuard, you do this by adding the following to your default.properties file:

proguard.config=proguard.cfg

(assuming proguard.cfg is the ProGuard configuration file created for you, or copied from a new project, into the project root folder.)


Thursday, April 28, 2011

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();
}
}