从子线程到主线程的Android通信

时间:2011-11-24 05:19:42

标签: android

我有一个带有主线程和子线程的android应用程序。我需要子线程定期向主线程发送消息。主线程反过来更新UI。我已经尝试使用处理程序,obtainMessage()和sendMessage()等来执行此过程,但是当主线程更新textView时我的应用程序失败,即使我将收到的消息打印到日志中并且它完全没问题。< / p>

所以我尝试了另一种在子线程中发布runnable来更新UI的方法

在主线程中:

public class Example extends Activity {
    public TextView mMatchesText;
    public Handler mHandler;  
    private ServerConnection conn;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMatchesText = (TextView) Example.this.findViewById(R.id.matches);
        mMatchesText.setText("Matches:\n");     /*this text appears when I run the app*/
        mHandler = new Handler();
        SessionEvents.addAuthListener(new SampleAuthListener());

 public class SampleAuthListener implements AuthListener {

        public void onAuthSucceed() {
            Example.this.runOnUiThread(new Runnable() {
                    public void run() {
                        conn = new ServerConnection(mProfile.toString());
                    }
                });
        }
   }

在子线程(ServerConnection.java)中:

/* constructor */
public ServerConnection()
{
    runner = new Thread(this);
    runner.start();
}


public void run()
{
    String fromServer;

    /** Establish connection to the server */

    /** Wait for messages from the server */
    while((fromServer = inFromServer.readLine()) != null)
    {
        mHandler.post(new Runnable(){
            @Override
            public void run(){
                Log.e("MY APP", fromServer);
                mMatchesText.setText(fromServer); 
            }
        });
    }
}

应用程序再次在第56行失败,这是 mMatchesText.setText(fromServer); formServer不为null,因为我将它打印到LogCat,它确实包含服务器发送的数据。

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): FATAL EXCEPTION: main
    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): java.lang.NullPointerException

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): at com.facebook.android.ServerConnection$1.run(ServerConnection.java:56) <--this is mMatches..

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): at android.os.Handler.handleCallback(Handler.java:587)

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): at android.os.Handler.dispatchMessage(Handler.java:92)

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): at android.os.Looper.loop(Looper.java:130)

    11-24 08:02:49.622: ERROR/AndroidRuntime(14571): at 

android.app.ActivityThread.main(ActivityThread.java:3683)

如果有帮助,mMatchesText在main.xml中声明如下:

<TextView android:id="@+id/matches"
android:textColor="@drawable/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/Login"
android:text=""
/>

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

mMatchesText在此处使用时为空:mMatchesText.setText(fromServer);

除非你向我们展示你的初始化,否则我们可以帮助你。