Satheesh Kumar R CyB Satheesh Kumar R CyB - 4 months ago 21
Android Question

Read a large text file into Textview

I want to read large file from sdcard into text view.
I have idea but i don't know how to apply.

I think this things need to use:
Handler And

But i dont know how to apply.
Anybody give some example or Tutorial.


Thread test=new Thread()
public void run()
File sfile=new File(extras.getString("sfile"));
try {
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(sfile));
String line1;

} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block

This is my code.But it is better than previous code,
but it is not able to read 2MB file.
How to slove this?
And How to set Progress?


Here's an example of how to do it. If the file is so large that it's going to take more than about 5 seconds to read, then it should probably just be an AsyncTask.

// first open the file and read it into a StringBuilder
String cardPath = Environment.getExternalStorageDirectory();
BufferedReader r = new BufferedReader(new FileReader(cardPath + "/filename.txt"));
StringBuilder total = new StringBuilder();
String line;
while((line = r.readLine()) != null) {

// then get the TextView and set its text
TextView txtView = (TextView)findViewById(;


You can only change UI elements in the UI thread. The documentation on threads has more details. When you try to do it from another thread, you get this (from your pastebin):

E/AndroidRuntime( 8517): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

I think the easiest solution is using AsyncTask, as I recommended before. You just put your work code in one function (doInBackground()) and your UI code in another (onPostExecute()), and AsyncTask makes sure they get called on the right threads and in order. The documentation I linked to has examples with loading bitmaps, which is just about the same thing as loading text.