在我的Android应用程序中,我有UI线程和子线程。子线程将消息发送到需要在TextView上打印的UI线程。我初始化UI线程中的TextView,我生成子线程,子线程将消息发送到UI线程,但UI线程在handleMessage()中失败。调试后,我发现HandleMessage()中的TextView为null。下面我展示了UI和子线程的代码。你能告诉我我做错了吗?
在UI主题中:
public class Example extends Activity {
public TextView mMatchesText;
public Handler mHandler;
private ServerConnection conn;
private String mProfile;
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*/
Example.this.runOnUiThread(new Runnable() {
public void run() {
if(mMatchesText == null)
Log.e("MY APP", "Before creating thread: mMatchesText is null");
else
Log.e("MY APP", "Before creating thread: mMatchesText is not null");
mProfile = FileReader.readFileAsString(getApplicationContext(), "profile.txt"));
conn = new ServerConnection(mProfile);
if(mMatchesText == null)
Log.e("MY APP", "After creating thread: mMatchesText is null");
else
Log.e("MY APP", "After creating thread: mMatchesText is not null");
}
});
}
Handler mHandler = new Handler(){
public void handleMessage(Message msg)
{
Log.e("MY APP", "In handler: Thread = " + Thread.currentThread().getName());
if(mMatchesText == null)
Log.e("MY APP", "In handler: mMatchesText is null");
else
Log.e("MY APP", "In handler: mMatchesText is not null");
Log.e("MY APP", "In handler: " + (String)msg.obj);
mMatchesText.setText((String)msg.obj);
}
};
请注意,在生成子线程之前和之后,TextView不为null。在Handler中,消息被正确接收,但TextView为null,即使它是正在执行处理程序的UI线程。
在子线程中:
public class ServerConnection extends Example implements Runnable
{
/* 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)
{
Message toMain = mHandler.obtainMessage();
toMain.obj = fromServer;
mHandler.sendMessage(toMain);
}
}
}
你能帮帮我吗。