I’m trying to implement a thread on a function that starts an HttpClient because it’s recomended according to d.android.com So I have implemented a thread but, it doesn’t seem to run as if I remove the thread code I see results.
This is my code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_box);// sd
TextView inbox = (TextView) findViewById(R.id.inbox);
final Functions function = new Functions();
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
where = prefs.getString("chat", "null");
class SendThread extends Thread {
public void run(){
//getInbox() runs an http client
listOfMessages = function.getInbox(where);
}
}
SendThread sendThread = new SendThread();
sendThread.start();
inbox.setText(listOfMessages);
}
Like I said above, if I remove my thread code, then it works perfectly. Any ideas on what I’m doing wrong? This is my first time using threads, sorry for any rookie mistakes.
I don’t get any errors (at least I don’t see any) but, I don’t see the output that I get without the thread code inserted.
I agree with the others: 1) you didn’t allow time for the thread to finish, and 2) you must modify the UI on the main thread. I figured you might want to see a concrete solution, so here you go:
The use of AsyncTask makes this super simple: it’s the Android-recommended way to do simple tasks off the main thread. When execute() is called, a new thread is created and it calls doInBackground(). Then the result is returned on the main thread to the onPostExecute method. So you don’t have to deal with runOnUiThread or anything else.
One thing to be aware of in this case: in the case of something like an orientation change, your Activity will be destroyed and recreated, and so the call getInbox() will be called again. This may or may not be a problem, depending on how long the method actually takes. If it’s unacceptable, you need something like a static AsyncTask, but then you run into the problem of attaching back to the new Activity. I’m just mentioning that, not because you have to handle it right now, but just so you’re aware.