【发布时间】:2017-04-06 08:14:21
【问题描述】:
我编写了简单的Loader 如下代码,我希望将数据添加到List,并且我的 RecyclerView 适配器通过使用notifyDataSetChanged() 刷新列表知道这一点
我的加载器类:
public class StringLoader extends AsyncTaskLoader<List<RobotViewModel>> {
private List<RobotViewModel> cache;
private static List<RobotViewModel> model;
public StringLoader(Context context) {
super(context);
}
@Override
protected void onStartLoading() {
if (cache == null) {
forceLoad();
} else {
super.deliverResult(cache);
}
}
@Override
public List<RobotViewModel> loadInBackground() {
Log.e("LOAD......... ", "new");
model = new ArrayList<>();
return model;
}
public void addCommand() {
RobotViewModel temp = new RobotViewModel();
temp.setMessage("hello");
temp.setMessageType(SV.RobotMessageType.SENT_BY_ROBOT.ordinal());
model.add(temp);
forceLoad();
}
@Override
public void deliverResult(List<RobotViewModel> data) {
cache = data;
super.deliverResult(data);
}
}
我使用活动中的addCommand() 方法:
public void clickOnSendCommand() {
loader.addCommand();
adapter.notifyDataSetChanged();
}
我的活动和实现适配器和加载器:
public class ActivityRegister extends BaseActivities {
private RobotMessagesAdapter adapter;
private StringLoader loader;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ActivityRegisterPresenter presenter = new ActivityRegisterPresenter(this);
ActivityRegisterViewModel viewModel = new ActivityRegisterViewModel();
binding.setViewModel(viewModel);
binding.setPresenter(presenter);
List<RobotViewModel> model = new ArrayList<>();
adapter = new RobotMessagesAdapter(this, model);
binding.registerRobot.setAdapter(adapter);
loader = (StringLoader) getSupportLoaderManager().initLoader(R.id.string_loader_id, null, loaderCallbacks);
}
private LoaderManager.LoaderCallbacks<List<RobotViewModel>> loaderCallbacks = new LoaderManager.LoaderCallbacks<List<RobotViewModel>>() {
@Override
public Loader<List<RobotViewModel>> onCreateLoader(int id, Bundle args) {
return new StringLoader(getApplicationContext());
}
@Override
public void onLoadFinished(Loader<List<RobotViewModel>> loader, List<RobotViewModel> data) {
adapter.setData(data);
}
@Override
public void onLoaderReset(Loader<List<RobotViewModel>> loader) {
adapter.setData(Collections.<RobotViewModel>emptyList());
}
};
setData() 适配器上的方法:
public void setData(List<RobotViewModel> data) {
list.clear();
list.addAll(data);
notifyDataSetChanged();
}
将项目添加到列表通常没有任何问题,并且工作正常,但我想向其中添加项目并刷新适配器
【问题讨论】:
-
@pskink 我不懂我的意思
-
@pskink 在这个源代码中
mObserver可以通过cursor.registerContentObserver(mObserver);注册我没有Cursor 而我的AsyncTaskLoader是List<RobotViewModel>不是Cursor,我该如何使用registerContentObserver? -
@pskink 我正在尝试在后台从数据库加载数据并在设备方向缓存数据
-
@pskink 好的,你能链接我如何在改变方向设备上缓存数据吗?我找不到这个功能
-
您是否使用过
saveInstancestate()方法来存储有关原始更改的数据。