Satheesh Kumar R CyB Satheesh Kumar R CyB - 1 month ago 11
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
Thread

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

Updated:

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;
while(null!=(line1=br.readLine()))
{
text.append(line1);
text.append("\n");
}
subtitletv.setText(text.toString());

} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
test.start();


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?

Answer

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) {
    total.append(line);
}
r.close();

// then get the TextView and set its text
TextView txtView = (TextView)findViewById(R.id.txt_view_id);
txtView.setText(total.toString());

EDIT

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.

Comments