我在我创建的一个片段中调用AsyncTaskLoader
。我已经导入了import android.app.LoaderManager;
,并且在调用此方法时遇到错误LoaderManager manager = getLoaderManager();
。我在主要活动中也有同样的事情,它不会抛出任何错误。
它还要求我导入这个android.support.v4.app.LoaderManager
而不是android.support.v4.app.LoaderManager
。当我这样做时,显示getLoaderManager()
已被弃用。
我的FragmentExchangeList.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.app.LoaderManager;
import android.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class FragmentExchangeList extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ExchangeListData>> {
private List<ExchangeListData> mExchangeListData;
private ListView mExchangeListView;
private AutoCompleteTextView mSetbaseCurrency;
private String linkForCurrencyList;
private static final int CURRENCY_List_LOADER_ID = 2;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_exchange_list, container, false);
mExchangeListData = new ArrayList<ExchangeListData>();
mExchangeListView = rootView.findViewById(R.id.exchange_list_view);
mSetbaseCurrency = rootView.findViewById(R.id.set_base_currency);
linkForCurrencyList = "https://ratesapi.io/api/latest?base="+mSetbaseCurrency.getText().toString();
LoaderManager manager = getLoaderManager();
manager.initLoader(CURRENCY_List_LOADER_ID, null, this);
return rootView;
}
@Override
public Loader<ArrayList<ExchangeListData>> onCreateLoader(int i, Bundle bundle) {
return new ExchangeListBackground(getContext(), linkForCurrencyList);
}
@Override
public void onLoadFinished(Loader<ArrayList<ExchangeListData>> loader, ArrayList<ExchangeListData> data) {
mExchangeListData.clear();
if(data != null && !data.isEmpty()){
mExchangeListData.addAll(data);
}
}
@Override
public void onLoaderReset(Loader<ArrayList<ExchangeListData>> loader) {
mExchangeListData.clear();
}
}
错误是error: incompatible types: android.support.v4.app.LoaderManager cannot be converted to android.app.LoaderManager
我过去也遇到过同样的问题。您使用的fragment
来自支持库,因此您需要将android.support.v4.app.LoaderManager
包用于LoadManager
。
但是搜索弃用,是因为谷歌正在弃用所有的加载器堆栈,他们建议使用Jobs。因此,要解决您的问题,请使用已弃用的软件包,并对Android Studio中添加一个禁止弃用的评论,这并不烦人。
删除import android.app.LoaderManager;
并添加此行import android.support.v4.app.LoaderManager