Fragment如何实现自定业务类中的CallBack回调?
在MainActivity中可以正常回调,但在fragment中就报错,fragment无法转换成context。请高手指教!感谢!********************************MainActivity中的调用方法********************************private void loadDatas(boolean useCache) { mChapterBiz.loadDatas(this, new ChapterBiz.CallBack() { @Override public void onSuccess(List chapterList) { mDatas.clear(); mDatas.addAll(chapterList); mAdapter.notifyDataSetChanged(); } @Override public void onFailed(Exception e) { e.printStackTrace(); } },useCache);}********************************这是自定义的业务类********************************package com.ray.expandablelistview.biz;import android.content.Context;import android.os.AsyncTask;import android.util.Log;import com.ray.expandablelistview.MainActivity;import com.ray.expandablelistview.bean.Chapter;import com.ray.expandablelistview.dao.ChapterDao;import com.ray.expandablelistview.utils.HttpUtils;import com.ray.expandablelistview.utils.ParseContent;import java.util.ArrayList;import java.util.List;import static com.ray.expandablelistview.MainActivity.TAG;public class ChapterBiz { private ChapterDao mChapterDao = new ChapterDao(); public void loadDatas(final Context context, final CallBack callback, boolean useCache){ AsyncTask asyncTask = new AsyncTask() { private Exception exception; @Override protected List doInBackground(Boolean... booleans) { boolean isUseCache = booleans[0]; List chapterList = new ArrayList(); //isUesCache为true就是本地数据库中有缓存数据,则使用本地数据中的缓存数据 try { if(isUseCache){ //TODO 本地数据库中有缓存数据,则从本地DB数据库中取数据 Log.e(TAG, "boolean isUseCache: "+isUseCache ); List chapterListFromDb = mChapterDao.loadFromDb(context); Log.e(TAG, "从本地数据缓存读取!"); chapterList.addAll(chapterListFromDb); } //如果本地没有缓存数据,或者取缓存数据失败,则向网络数据源发起数据请求 if(chapterList.isEmpty()){ //封装一个网络请求数据的方法loadFromNet,并在此调用 List chapterListFromNet = loadFromNet(context); //将网络请求到的数据chapterListFromNet通过ChapterDao.insertToDb()方法写入缓存数据库 mChapterDao.insertToDb(context,chapterListFromNet); Log.e(TAG, "从网络获取数据,并写入本地缓存数据库!"); chapterList.addAll(chapterListFromNet); } }catch (Exception e){ this.exception=e; Log.e(TAG, "mChapterDao.insertToDb: "+e); } return chapterList; } @Override protected void onPostExecute(List chapterList) { if(exception != null){ callback.onFailed(exception); return; } callback.onSuccess(chapterList); } }; asyncTask.execute(useCache); } private List loadFromNet(Context context) { List chapterList = new ArrayList(); String url = "https://www.tianmg.com/api/expandablelistview"; //第一步:发请求获取String数据(通过调用自建方法HttpUtils实现) String content = HttpUtils.doGet(url); //Log.e(TAG, "content: "+content ); //第二步:将获取到的数据内容解析为List(通过调用自建方法parseContent实现) if(content != null){ chapterList = ParseContent.doParse(content); //Log.e(TAG, "loadFromNet: "+"chapterList:"+chapterList ); } return chapterList; } public static interface CallBack{ void onSuccess(List chapterList); void onFailed(Exception e); }} |
免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。
版权声明:作者保留权利,不代表天盟立场。
|
|
|
|