I’m using AsyncTask to download and parse data in a separate thread and I need to pass in the values returned by loadXml into the database.
The problem is that I can’t instantiate the database because it requires a context and my DownloadXmlTask is in a separate class to the activity class where it is instantiated.
How do I use pass the values into the database if I can’t instantiate the database class?
Code Sample:
public class DownloadXmlTask extends AsyncTask<String,Void,Void>{
public static final String TAG = "VotingApp";
@Override
protected Void doInBackground(String... urls) {
try {
// Get the parsed list of Candidate objects
ArrayList<Candidate> candidatesList = loadXml(urls[0]);
CandidatesDatabaseHelper db = new CandidatesDatabaseHelper(getApplicationContext()); <---- ERROR (I know I can't use getApplicationContext() here)
// Insert the candidates into the database
for(Candidate c : candidatesList){
//NOT FINISHED
}
} catch (IOException e) {
Log.d(TAG, "Error " + e);
} catch (XmlPullParserException e) {
Log.d(TAG, "Error " + e);
}
Log.d(TAG, "NOT WORKING");
return null;
}
You could solve that problem by making AsyncTask an inner class, but if you just do it the way you are currently doing it then technically you could do
AsyncTask<Object,Void,Void>:instead of
String. When calling.execute(this, someString), send it the Context first and the String second. Then you just cast each of them into their appropriate variables. Try that and let me know if it works. Can’t test it out right now unfortunately so you’re going to have to test it.