我有一個帶有主線程和子線程的android應用程序。我需要子線程定期發送消息到主線程。主線程依次更新UI。我試圖使用處理程序,acquireMessage()和sendMessage()等來執行此過程,但是當主線程更新textView時,即使我將收到的消息打印到日誌中,它仍然很好,但是我的應用程序失敗。從子線程到主線程的Android通信
所以,我想發佈一個可運行的子線程更新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不爲空,因爲我將它打印到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=""
/>
燦有人幫忙?
好像來自服務器是空的 – ngesh
發佈nMatchesText初始化的代碼 – Jack