Skip to content

Commit

Permalink
新增数据缓存机制
Browse files Browse the repository at this point in the history
新增
1.新增文章列表缓存
2.新增最新文章详细缓存
3.新增目录列表数据缓存
  • Loading branch information
zhongzilu committed Nov 2, 2016
1 parent ea7804c commit ad60a97
Show file tree
Hide file tree
Showing 5 changed files with 211 additions and 176 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public void onCreate() {

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkBroadcastReceiver();
//registerReceiver(receiver, filter);
// registerReceiver(receiver, filter);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package com.zhongzilu.bit100.application.helper;

import android.content.Context;
import com.zhongzilu.bit100.application.App;

/**
* JSON数据缓存帮助类
* Created by zhongzilu on 2016-11-02.
*/
public class CacheHelper {

private static final String CACHE_FILE = "POSTS_CACHE",
ITEM_POSTS_ALL = "posts_all",
ITEM_POSTS_RECENT = "posts_recent",
ITEM_ALL_CATEGORIES = "all_categories";

public static void savePostsAll(final String json){
new Thread(new Runnable() {
@Override
public void run() {
App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.edit()
.putString(ITEM_POSTS_ALL, json)
.apply();
}
}).start();
}

public static String getPostsAll(){
return App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.getString(ITEM_POSTS_ALL, null);
}

public static void saveRecentPosts(final String json){
new Thread(new Runnable() {
@Override
public void run() {
App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.edit()
.putString(ITEM_POSTS_RECENT, json)
.apply();
}
}).start();
}

public static String getRecentPosts(){
return App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.getString(ITEM_POSTS_RECENT, null);
}

public static void saveAllCategories(final String json){
new Thread(new Runnable() {
@Override
public void run() {
App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.edit()
.putString(ITEM_ALL_CATEGORIES, json)
.apply();
}
}).start();
}

public static String getAllCategories(){
return App.getAppContext()
.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
.getString(ITEM_ALL_CATEGORIES, null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;
import com.zhongzilu.bit100.R;
import com.zhongzilu.bit100.application.helper.CacheHelper;
import com.zhongzilu.bit100.application.util.LogUtil;
import com.zhongzilu.bit100.application.util.RequestUtil;
import com.zhongzilu.bit100.model.bean.ArticleDetailBean;
Expand Down Expand Up @@ -100,30 +101,30 @@ private void initWebView() {

// mWebView.setInitialScale(0); // 改变这个值可以设定初始大小

//重要,用于与页面交互!
// mWebView.addJavascriptInterface(new Object() {
// @SuppressWarnings("unused")
// public void oneClick(final String locX, final String locY) {//此处的参数可传入作为js参数
// mHandler.post(new Runnable() {
// public void run() {
// mWebView.loadUrl("javascript:shows(" + locX + "," + locY + ")");
// }
// });
// }
// }, "demo");//此名称在页面中被调用,方法如下:
//<body onClick="window.demo.clickOnAndroid(event.pageX,event.pageY)">
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
LogUtil.d(TAG, "setUserVisibleHint: " + isVisibleToUser);
if (isVisibleToUser && isFirst){
loadLocalRecentPostsCache();
RequestUtil.getRecentPost(this);
isFirst = false;
}
}

private void loadLocalRecentPostsCache() {
try {
String json = CacheHelper.getRecentPosts();
if (!TextUtils.isEmpty(json)){
handleRecentPostsResponse(new JSONObject(json));
}
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
Expand Down Expand Up @@ -224,40 +225,14 @@ public void onStart(int what) {}

@Override
public void onSucceed(int what, Response<JSONObject> response) {

try {
String status = response.get().getString("status");
if ("ok".equals(status)) {
switch (what){
case RequestUtil.TAG_GET_RECENT_POST:
AllPostsResponse result = new Gson()
.fromJson(response.get().toString(), AllPostsResponse.class);
//注意:
// 之所以要判断result.posts.length > 1,是因为获取首页的数据时,返回了置顶的
// 一篇文章,如果后台取消了置顶的文章,这里的Gson解析会出错
if (result.posts.length > 1){
mBean = result.posts[1];
mContent = formatContent(mBean.content);
} else {
mBean = result.posts[0];
mContent = formatContent(mBean.content);
}
break;

case RequestUtil.TAG_GET_POST_BY_ID:
JSONObject obj = response.get().getJSONObject("post");
String content = obj.getString("content");
mContent = formatContent(content);
break;
}
mWebView.loadUrl("file:///android_asset/index.html");

} else {
Toast.makeText(getActivity(), response.get().getString("error"), Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
switch (what){
case RequestUtil.TAG_GET_RECENT_POST:
handleRecentPostsResponse(response.get());
CacheHelper.saveRecentPosts(response.get().toString());
break;
case RequestUtil.TAG_GET_POST_BY_ID:
handlePostByIdResponse(response.get());
break;
}
}

Expand All @@ -278,4 +253,51 @@ public void onFinish(int what) {}
private String formatContent(String content){
return "\"" + content.replaceAll("\"", "'") + "\"";
}

private void handleRecentPostsResponse(JSONObject object){
try {
String status = object.getString("status");
if ("ok".equals(status)) {

AllPostsResponse result = new Gson()
.fromJson(object.toString(), AllPostsResponse.class);
//注意:
// 之所以要判断result.posts.length > 1,是因为获取首页的数据时,返回了置顶的
// 一篇文章,如果后台取消了置顶的文章,这里的Gson解析会出错
if (result.posts.length > 1){
mBean = result.posts[1];
mContent = formatContent(mBean.content);
} else {
mBean = result.posts[0];
mContent = formatContent(mBean.content);
}

mWebView.loadUrl("file:///android_asset/index.html");

} else {
Toast.makeText(getActivity(), object.getString("error"), Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}

private void handlePostByIdResponse(JSONObject object){
try {
String status = object.getString("status");
if ("ok".equals(status)) {
JSONObject obj = object.getJSONObject("post");
String content = obj.getString("content");
mContent = formatContent(content);

mWebView.loadUrl("file:///android_asset/index.html");
} else {
Toast.makeText(getActivity(), object.getString("error"), Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
Expand All @@ -24,6 +22,7 @@
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;
import com.zhongzilu.bit100.R;
import com.zhongzilu.bit100.application.helper.CacheHelper;
import com.zhongzilu.bit100.application.util.LogUtil;
import com.zhongzilu.bit100.application.util.RequestUtil;
import com.zhongzilu.bit100.model.bean.CategoriesBean;
Expand All @@ -33,6 +32,7 @@
import com.zhongzilu.bit100.model.response.AllCategoriesResponse;
import com.zhongzilu.bit100.view.activity.Bit100ArticleListActivity;
import com.zhongzilu.bit100.view.adapter.CategoryRecyclerViewAdapter;
import com.zhongzilu.bit100.view.adapter.MainRecyclerViewAdapter;
import com.zhongzilu.bit100.view.adapter.listener.MyItemClickListener;
import com.zhongzilu.bit100.view.adapter.listener.MyItemLongClickListener;

Expand Down Expand Up @@ -79,7 +79,6 @@ public void onRefresh() {
mPushList.clear();
addTagsTestData();
RequestUtil.getAllCategories(Bit100CategoryFragment.this);
// simulationNetWorkDataHandler.sendEmptyMessageDelayed(0, 2000);
}
});

Expand Down Expand Up @@ -118,12 +117,6 @@ public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
isLoadMore = false;
// return;
// }

// addTestDate();
// mAdapter.notifyItemRemoved(mAdapter.getItemCount());
// mAdapter.notifyDataSetChanged();
// isLoadMore = false;

}
}

Expand All @@ -139,7 +132,7 @@ public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
}
});

addTagsTestData();
mPushList.add(new PushModel(MainRecyclerViewAdapter.TYPE_NULL, new Object()));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setVisibility(View.VISIBLE);
}
Expand All @@ -156,43 +149,19 @@ private void addTagsTestData(){
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isFirst){
// simulationNetWorkDataHandler.sendEmptyMessageDelayed(0, 2000);
loadLocalCategoriesCache();
RequestUtil.getAllCategories(this);
isFirst = false;
}
}

private void addTestDate() {
for (int i = 0; i < 10; i++){
mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_CATEGORY, new Object()));
}
private void loadLocalCategoriesCache(){
// String json = CacheHelper.getAllCategories();
// if (!TextUtils.isEmpty(json)){
// handleCategoryResponse(json);
// }
}

private Handler simulationNetWorkDataHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

//添加数据
// if (mPushList.isEmpty()) {
// mPushList.clear();
//
// mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_ITEM_DECORATOR, new ItemDecoratorBean("标签", "")));
//
// mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_TAGS, new TagsBean(getResources().getStringArray(R.array.tags))));
//
// mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_ITEM_DECORATOR, new ItemDecoratorBean("目录", "")));

// addTestDate();
// }

// mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.setVisibility(View.VISIBLE);
if (mRefresh.isRefreshing())
mRefresh.setRefreshing(false);
}
};

@Override
public void onItemClick(RecyclerView.ViewHolder holder, View view, int position) {
int type = mPushList.get(position).getPushType();
Expand Down Expand Up @@ -243,24 +212,12 @@ public void onStart(int what) {
@Override
public void onSucceed(int what, Response<String> response) {
LogUtil.d(TAG, "onSucceed: " + response);
AllCategoriesResponse result = new Gson().fromJson(response.get(),
new TypeToken<AllCategoriesResponse>(){}.getType());
if ("ok".equals(result.status)){
mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_ITEM_DECORATOR,
new ItemDecoratorBean("目录", String.valueOf(result.categories.length)) ));

for (CategoriesBean cb : result.categories){
mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_CATEGORY, cb));
}

} else {
Toast.makeText(getActivity(), result.error, Toast.LENGTH_SHORT).show();
switch (what){
case RequestUtil.TAG_GET_ALL_CATEGORIES:
handleCategoryResponse(response.get());
CacheHelper.saveAllCategories(response.get());
break;
}

mAdapter.notifyDataSetChanged();
mRecyclerView.setVisibility(View.VISIBLE);
if (mRefresh.isRefreshing())
mRefresh.setRefreshing(false);
}

@Override
Expand All @@ -281,4 +238,28 @@ public void onFinish(int what) {
}
};
}

private void handleCategoryResponse(String json){
AllCategoriesResponse result = new Gson().fromJson(json,
new TypeToken<AllCategoriesResponse>(){}.getType());
if ("ok".equals(result.status)){
mPushList.clear();
addTagsTestData();

mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_ITEM_DECORATOR,
new ItemDecoratorBean("目录", String.valueOf(result.categories.length)) ));

for (CategoriesBean cb : result.categories){
mPushList.add(new PushModel(CategoryRecyclerViewAdapter.TYPE_CATEGORY, cb));
}

} else {
Toast.makeText(getActivity(), result.error, Toast.LENGTH_SHORT).show();
}

mAdapter.notifyDataSetChanged();
mRecyclerView.setVisibility(View.VISIBLE);
if (mRefresh.isRefreshing())
mRefresh.setRefreshing(false);
}
}
Loading

0 comments on commit ad60a97

Please sign in to comment.