AsyncTask未执行

时间:2019-02-14 08:12:49

标签: android-asynctask android-jetpack android-viewmodel

我正在关注以下示例: 14.1A: Working with Architecture Components: Room, LiveData, ViewModel

,并且我已经建立了我的存储库,该存储库为使用异步任务加载网络数据(解析xml),但这从未执行。这里简化了代码:

public class CarSoundsRepository {

private MutableLiveData<List<CarEntry>> mAllCars;

CarSoundsRepository(Application application) {
    new loadDataAsyncTask().execute();
}

LiveData<List<CarEntry>> getAllCars () {
    return mAllCars;
}

private  class loadDataAsyncTask extends AsyncTask<Void, Void, List<CarEntry>> {

    @Override
    protected List<CarEntry> doInBackground(Void... voids) {
        List<CarEntry> carlist = null;
        InputStream is = null;
        try {
            is = new URL("https://urllink").openStream();
        } catch (IOException e) {
            Log.e(TAG, "IO exception "+e);
        }
        if (is != null) {
            try {
                carlist =  new MyXmlParser().parse(is);
            } catch (XmlPullParserException e) {
                Log.e(TAG,"XML Pareser exception "+e);
            } catch (IOException e) {
                Log.e(TAG,"IO exception" + e);
            }
        }
        return carlist;
    }

    @Override
    protected void onPostExecute(List<CarEntry> carEntries) {
        mAllCars.setValue(carEntries);
    }
}

}

此存储库在我的ViewModel实例中实例化:

mRepository = new CarSoundsRepository(application);

我在活动中得到了ViewModel:

 mViewModel = ViewModelProviders.of(this).get(CarSoundsViewModel.class);

一切正常,除了不执行loadDataAsyncTask。调用execute()方法,但从不使用doInBackground方法。

有什么想法吗?

0 个答案:

没有答案