我正在尝试将上下文传递给自定义Loader,但我得到的类型不匹配。在onCreateLoader
return new NewsLoader(CONTEXT, url);
我尝试使用getActivity()
和getContext()
以及getApplicationContext()
方法作为输入。
错误;
getContext()
“必需的android.support.v4.loader <java.util.arraylist<com.example.android.greennewswire.News>
this
NewsLoader(android.content.Context,String)无法应用于(com.example.android.greennewswire.NewsFragmentBBC,String)
`package com.example.android.greennewswire;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class NewsFragmentBBC extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<News>>{
//String object holding the network request URL to be passed into the Loader
private static final String NEWS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=android";
public NewsFragmentBBC() {
// Required empty public constructor
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list, container, false);
//Create a LoaderManager and initialise the Loader
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(1, null, this);
return rootView;
}
@Override
public Loader<ArrayList<News>> onCreateLoader(int id, Bundle args) {
return new NewsLoader(this, NEWS_REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<ArrayList<News>> loader, ArrayList<News> data) {
}
@Override
public void onLoaderReset(Loader<ArrayList<News>> loader) {
}
}
NewsLoader类
package com.example.android.greennewswire;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.ArrayList;
public class NewsLoader extends AsyncTaskLoader<ArrayList<News>> {
private String mUrl;
//Default constructor to take input objects
public NewsLoader (Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public ArrayList<News> loadInBackground() {
//Null check
if (mUrl == null) {
return null;
}
ArrayList<News> news = QueryUtils.fetchNewsData(mUrl);
return news;
}
}
答案 0 :(得分:0)
我通过将LoaderManager的导入库从android.support.v4.app.LoaderManager
更改为android.app.LoaderManager
并确保实现的回调与该库匹配来解决此问题。然后我能够在我的getContext()
参数中使用NewsLoader
方法而没有问题。