Issue
I am writiing a java application on Android. I have an Activity which starts an AsyncTask in order to get data from server and the to present it.
I am trying to present the data in onPostExecute() method but some how setContentView & populateUI(getApplicationContext()) not resolved in its scope. Why?
If run a code like this, without adding setContentView I get an empty screen at the end of execution. No exception appears.
public class CurrencyRatesActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new ReadCurrencyRateTask(this).execute("http://currency.xml");
}
}
public class ReadCurrencyRateTask extends AsyncTask<String, Integer, Integer>
{
private Context mainActivityContext;
public ReadCurrencyRateTask(Context mainActivityContext)
{
super();
this.mainActivityContext = mainActivityContext;
}
public Integer doInBackground(String... url)
{
// do some culculations
.......
return status;
}
protected void onPostExecute(Integer result)
{
// In case connection succeeded
TableLayout tbl = new TableLayout(mainActivityContext);
tbl.setStretchAllColumns(true);
tbl.bringToFront();
for (int i=0; i<currencyList.size(); i++)
{
TableRow tr = new TableRow(mainActivityContext);
TextView country = new TextView(mainActivityContext);
country.setText("...something...");
tr.addView(country);
}
}
}
Thanks
Solution
Actually you only answered your question "not resolved in its scope" and really it is.
try this
public class CurrencyRatesActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new ReadCurrencyRateTask(this).execute("http://currency.xml");
}
class ReadCurrencyRateTask extends AsyncTask<String, Integer, Integer> {
//your network stuff goes here
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
//your stuff
setContentView(yourView);
}
}
}
- Declare the AsyncTask inside activity so that you access all the activity methods.
- Or If you have AsyncTask in separate class then use interface as callbacks and do Update UI stuff in activity.
Important : You can update UI only from UI thread and from Activity.
Answered By - Bharatesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.