I have one main activity that handles all the UI stuff. In the activity i have a ListView
which is in a SlidingDrawer
, above that are 4 TextView
s.
I want to change the text of the 4 TextView
开发者_JS百科s once i click on an item from the ListView
.
I get the text from an online database, so i put the code for that in an extra class.
I created a reference to the workerclass:
final OneTopic ot = new OneTopic();
In my onClickListener I call the method from the workerclass
ot.postData(position);
At the beginning of the workerclass i have a reference to the main class
Main main = new Main();
when the worker class is finished, it calls the method that updates the UI in the Activity.
main.displayText(body, title, date, poster);
The method its calling looks like this:
public void displayText(String body, String title, String date, String poster) {
tx_body.setText(Html.fromHtml(body));
tx_title.setText(title);
tx_date.setText(date);
tx_poster.setText(poster);
}
If I do this my app force closes once it tries to set the text.
What am I doing wrong?At the beginning of the workerclass i have a reference to the main class
Main main = new Main();
That's actually creating a new instance of your Main class, not getting a reference to the current one. If you want a reference to your activity from your worker thread, then you need to pass in your activity as a parameter.
ot.postData(Main.this, position);
Without seeing your entire code, I see two possibilities:
Your WorkerThread is not running in the UI Thread and you can only update UI objects from within the UI Thread. Check out the Worker Threads topic in the Android dev guide. Basically the code for displayText() is what needs to go in the Runnable in the example I just provided you.
I am slightly troubled at this statement:
At the beginning of the workerclass i have a reference to the main class
Main main = new Main();
If Main is your activity, then you should not be constructing a new one. You need a reference to the Activity instance that started the worker thread.
Hope this helps. I see you're new to StackOverflow. If this answers your question, please mark it as accepted. Good luck!
精彩评论