2

我正在使用 AsyncTask 在单独的线程中下载和解析数据,我需要将 loadXml 返回的值传递到数据库中。

问题是我无法实例化数据库,因为它需要一个上下文,而我的 DownloadXmlTask​​ 与实例化它的活动类位于一个单独的类中。

如果我无法实例化数据库类,如何使用将值传递到数据库中?

代码示例:

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;
}
4

1 回答 1

0

您可以通过使 AsyncTask 成为内部类来解决该问题,但是如果您只是按照当前的方式进行操作,那么从技术上讲,您可以这样做AsyncTask<Object,Void,Void>

@Override
protected Void doInBackground(Object... urls) {
    Context context = (Context)urls[0]; //should always be true by your own rules
    /*then you can also loop the urls for the rest of the Strings to cast
    **if there are going to be more. Or not. Your choice*/
//.....

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.

于 2012-12-08T02:07:02.597 回答