Reputation: 16002
I have to load XML data in my app, I'm doing that in a subclass of my activity class extending AsyncTask like this :
public class MyActivity extends Activity {
ArrayList<Offre> listOffres;
private class DownloadXML extends AsyncTask<Void, Void,Void>
{
protected Void doInBackground(Void... params)
{
listOffres = ContainerData.getFeeds();
return null;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_liste_offres);
DownloadXML.execute(); // Problem here !
for(Offre offre : listOffres) { // etc }
}
}
I don't know how to use execute() here, I have the following error :
Cannot make a static reference to the non-static method execute(Integer...) from the type AsyncTask
I guess some parameters but what ?
Thank you.
Upvotes: 7
Views: 25327
Reputation: 8305
Well if you want to execute some code by async task in java you can also do this:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
// add code which you want to run in background thread
runOnUiThread(new Runnable() {
@Override
public void run() {
// add code which you want to run in main(UI) thread
}
});
}
});
And in kotlin if you are using anko, there is much more simpler way to acheive this:
doAsync {
// add code which you want to run in background thread
uiThread {
// add code which you want to run in main(UI) thread
}
}
Upvotes: 2
Reputation: 25
You have to create object of DownloadXML class first.
DownloadXML downloadxml= new DownloadXML();
downloadxml.execute();
and return listOffres.
listOffres = ContainerData.getFeeds();
return listOffers;
Upvotes: 0
Reputation: 8856
Actually you are calling the method of AsyncTask (which further extends the AsyncTask class) without making an OBJECT of that class. you can call the execute method in two ways.
make an object/instance of the class like
DownloadXML task=new DownloadXML();
task.execute();
by using an flying object.
new DownloadXML().execute();
I prefer to use here 2nd method to do that.
Upvotes: 1
Reputation: 7605
u can execute ur asynctask either
new DownloadXML().execute();
or
DownloadXML task=new DownloadXML();
task.execute();
and one more thing u are getting in array in asynctask than it is good to use postexeceute method for ur for loop iteration
as given below
protected void onPostExecute(String s) {
for(Offre offre : listOffres) { // do ur work here after feeling array }
}
Upvotes: 0
Reputation: 72331
You need to create an instance of your DonwloadXML
file and call execute()
on that method:
DownloadXML task=new DownloadXML();
task.execute();
EDIT: you should probably also return the listOffers
from your doInBackground()
and process the array in the onPostExecute()
method of your AsynTask
. You can have a look at this simple AsyncTask tutorial.
Upvotes: 17