简体   繁体   中英

Cannot display the message in TextView using thread

It is a prat of an android app, this app want to connect with other android devices. I want to display the message on the TextView that I have received from the server. But there have error in this line, tv.setText(message);

There are the error:

java.lang.NullPointerException
FATAL EXCEPTION: Thread-10

Please help me show the message in the TextView, thanks.

class ReadMes extends Thread{

private Socket socket;
private TextView tv;

public ReadMes(Socket socket, TextView tv){
    this.socket = socket;
    this.tv = tv;
}

@Override
public void run() {
    BufferedReader reader = null;

    try{
        reader = new BufferedReader( new InputStreamReader(socket .getInputStream()));
        String message = null;
        while( true){
            message = reader.readLine();

            tv.setText(message);
        }
    } catch(IOException e){
        e.printStackTrace();
    } finally{
        if( reader!= null){
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

}

You can't modify anything on the screen from a background thread.

You need to either use a Handler to communicate from your background thread to the UI Thread and have the handler change the TextView for you OR you can use an AsyncTask to abstract away the Thread/Handler interaction into one "easier to use" package.

Try to use

runOnUiThread(new Runnable() {
    public void run() {
        tv.setText(message);
    }
}).start();

instead of

tv.setText(message);

As you are trying to update textView from worker thread but "do not access the Android UI toolkit from outside the UI thread"

http://developer.android.com/guide/components/processes-and-threads.html

To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:

  1. Activity.runOnUiThread(Runnable)
  2. View.post(Runnable)
  3. View.postDelayed(Runnable, long)

So use it like , ie put this line tv.setText(message); inside the runOnUiThread

runOnUiThread(new Runnable() {

            @Override
            public void run() {
            tv.setText(message);    
            }
        });

Or

           tv.post(new Runnable() {
                public void run() {
                    tv.setText(message);    
                }
            });

Hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM