Read a large text file into Textview

后端 未结 4 1450
逝去的感伤
逝去的感伤 2021-01-03 00:03

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 d

相关标签:
4条回答
  • 2021-01-03 00:43

    UI can be updated by using this also:

    runOnUiThread(new Runnable() {
           @Override
           public void run() {
    
           }
    });
    
    0 讨论(0)
  • 2021-01-03 00:46

    Create a new thread then using openFileforInput read all file data into StringBuffer.

    Use TextView.setText() method to set data.

    0 讨论(0)
  • 2021-01-03 00:49

    Your problem is that you are accessing a View owned by the GUI thread from the thread that is reading your file:

    subtitletv.setText(text.toString());
    

    You need to read the file, then pass its contents to the main thread to be displayed.

    //Create a handler on the UI Thread:
    private Handler mHandler = new Handler();
    
    //Executed in a non-GUI thread:
    public void updateView(){
        final String str = TheDataFromTheFile;
        mHandler.post(new Runnable(){
            @Override
            public void run() {
                 subtitletv.setText(str);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 01:01

    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.

    0 讨论(0)
提交回复
热议问题