Reputation: 960
I want to publish the result of my AsyncTask (a string) in a textView.
Here is my Main:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadRss readRss=new ReadRss(this);
readRss.execute();
......
}
Here is my AsyncTask:
public class ReadRss extends AsyncTask<Void,Void,Void> {
public ReadRss(Context context){
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(Void aVoid) {
}
@Override
protected Void doInBackground(Void... params) {
ProcessXml();
return null;
}
private void ProcessXml() {
//HERE CREATE MY STRING
String myresult="example";
TextView txt_ris = (TextView)findViewById(R.id.txt_ris); <---HOW CAN I DO THIS?
txt_ris.setText(myresult);
}
}
}
}
FindViewById don't work in the AsyncTask so how can i get the TextView in here? Maybe i can pass it as a paramiter in the AsyncTask, What is the syntax?
Upvotes: 1
Views: 598
Reputation: 2608
You need to place UI work in onPostExecute
method, since doInBackground executes in not UI thread
public class ReadRss extends AsyncTask<Void,Void,String> {
public ReadRss(Context context){
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(String string) {
TextView txt_ris = (TextView)findViewById(R.id.txt_ris);
txt_ris.setText(myresult);
}
@Override
protected String doInBackground(Void... params) {
return ProcessXml();
}
private String ProcessXml() {
//HERE CREATE MY STRING
return "example";
}
}
Upvotes: 2
Reputation: 3107
For your TextView to be correctly referenced you need a context and you already have a reference to your starting Activity in your AsyncTask constructor, so you can do something like:
public class ReadRss extends AsyncTask<Void,Void,Void> {
private TextView tv;
private YourStartingActivity activity;
public ReadRss(Context context){
activity = (YourStartingActivity)context;
tv = (TextView)activity.findViewById(R.id.txt_ris)
}
@Override
protected void onPreExecute() {
...
}
@Override
protected void onPostExecute(Void aVoid) {
(follow Michael Spitsin instructions here)
}
@Override
protected Void doInBackground(Void... params) {
...
}
}
Upvotes: 1