private void getFromCloud() { try { groups = new ArrayList<>(); AVUser user = AVUser.getCurrentUser(); JSONArray array = user.getJSONArray("groups"); if (array != null) { for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); WrapGroup wrapGroup = new WrapGroup(); Group group = new Group(); group.setWidth(236); group.setHeight(354); group.setImageurl(object.getString("imageurl")); group.setTitle(object.getString("title")); group.setUrl(object.getString("url")); wrapGroup.setGroup(group); wrapGroup.setIscollected(true); wrapGroup.setDate(new Date().getTime()); wrapGroup.setGroupid(object.getString("groupid")); groups.add(wrapGroup); } saveDb(groups); mAdapter.replaceWith(groups); showSnackBar("云端同步成功"); } } catch (JSONException e) { e.printStackTrace(); KLog.e(e); } }
private void saveToCloud() { try { JSONArray array = new JSONArray(); for (WrapGroup group : groups) { JSONObject object = new JSONObject(); object.put("groupid", group.getGroupid()); object.put("title", group.getGroup().getTitle()); object.put("imageurl", group.getGroup().getImageurl()); object.put("url", group.getGroup().getUrl()); array.put(object); } AVUser user = AVUser.getCurrentUser(); user.put("groups", array); user.saveInBackground( new SaveCallback() { @Override public void done(AVException e) { if (e == null) { showSnackBar("云端同步完成"); } } }); } catch (JSONException e) { e.printStackTrace(); KLog.e(e); } }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("我的收藏"); groups = WrapGroup.all(realm); KLog.e(groups.size()); mAdapter = new CollectedAdapter(this) { @Override protected void onItemClick(View v, int position) { startGroupActivity(v, position); } }; mRecyclerView.setAdapter(mAdapter); if (groups.size() > 0) { // 本地有数据才去上传 mAdapter.replaceWith(groups); if (mHasUser) { // 已经登录 saveToCloud(); } else { showSnackBar("可以登录进行云端同步啦"); } } else if (mHasUser) { // 本地没有 并且已经登录 getFromCloud(); } else { showSnackBar("可以登录进行云端同步啦"); } }
@Override public void onRefresh() { List<WrapGroup> groups = WrapGroup.all(realm); mAdapter.replaceWith(groups); mRefresher.setRefreshing(false); }