在Android中如何实现JSON的离线缓存? [英] How can implement offline caching of json in Android?
问题描述
我工作的一个应用程序的文章像TechCrunch的我从JSON解析数据。 我解析标题,作者和图像来自JSON。 文章显示在列表视图。 我想要做的脱机缓存是指在没有互联网的用户可以阅读的文章。
下面是我的code -
公共类OneFragment扩展片段{
公共OneFragment(){}
私有静态最后字符串变量= OneFragment.class.getSimpleName();
//电影JSON网址
私有静态字符串URL =HTTP:// URL;
私人ProgressDialog pDialog;
私人名单,其中,电影> movieList =新的ArrayList<电影>();
私人的ListView ListView的;
私人CustomListAdapter适配器;
INT current_page = 0;
INT米preLAST;
SwipeRefreshLayout swipeView;
@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
捆绑savedInstanceState){
最后查看rootView = inflater.inflate(R.layout.swip,集装箱,假);
swipeView =(SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
swipeView.setColorScheme(android.R.color.holo_blue_dark,android.R.color.holo_blue_light,android.R.color.holo_green_light,android.R.color.holo_green_dark);
pDialog =新ProgressDialog(getActivity());
pDialog.setMessage(载入中...);
pDialog.show();
pDialog.setCancelable(假);
swipeView.setOnRefreshListener(新SwipeRefreshLayout.OnRefreshListener(){
@覆盖
公共无效onRefresh(){
// TODO自动生成方法存根
swipeView.setRefreshing(真正的);
Log.d(刷卡,刷新数);
(新处理程序())。postDelayed(新可运行(){
@覆盖
公共无效的run(){
// TODO自动生成方法存根
swipeView.setRefreshing(假);
ONSTART();
}
},3000);
}
});
ListView控件=(ListView控件)rootView.findViewById(R.id.list49);
listView.setOnScrollListener(新AbsListView.OnScrollListener()
{
@覆盖
公共无效onScrollStateChanged(AbsListView absListView,int i)以
{
}
@覆盖
公共无效onScroll(AbsListView观点,诠释firstVisibleItem,诠释visibleItemCount,INT totalItemCount)
{
INT lastItem = firstVisibleItem + visibleItemCount;
如果(lastItem == totalItemCount){
如果(M preLAST!= lastItem)
{
米preLAST = lastItem;
pDialog =新ProgressDialog(getActivity());
pDialog.setMessage(加载更多的文章......);
pDialog.show();
//pDialog.setCancelable(false);
ONSTART();
}
}
}
});
listView.setOnItemClickListener(新OnItemClickListener(){
@覆盖
公共无效onItemClick(适配器视图<>适配器视图,视图中查看,INT位置,
长偏移){
// TODO自动生成方法存根
电影项=(动画)adapter.getItem(位置);
意向意图=新的意图(rootView.getContext(),SingleArticle.class);
single.title = item.getTitle();
single.author = item.getAuthor();
startActivity(意向);
}
});
// pDialog =新ProgressDialog(本);
//显示进度对话框发出HTTP请求之前
返回rootView;
}
@覆盖
公共无效的OnStart(){
super.onStart();
//调用接口的变化在这里,只
//避免getactivity()空
//增加当前页面
current_page + = 1;
//下一个页面请求
URL =HTTP:// URL+ current_page;
//适配器=新CustomListAdapter(这一点,movieList);
INT currentPosition = listView.getFirstVisiblePosition();
适配器=新CustomListAdapter(getActivity(),movieList);
listView.setAdapter(适配器);
listView.setSelectionFromTop(currentPosition + 1,0);
//改变动作栏颜色
// getActivity()。getActionBar()的setBackground(
//新ColorDrawable(Color.parseColor(#1b1b1b)));
//创建凌空要求OBJ
JsonArrayRequest movieReq =新JsonArrayRequest(URL,
新Response.Listener< JSONArray>(){
@覆盖
公共无效onResponse(JSONArray响应){
Log.d(TAG,response.toString());
hidePDialog();
//解析JSON
的for(int i = 0; I< response.length();我++){
尝试 {
JSONObject的OBJ = response.getJSONObject(我);
动画电影=新电影();
movie.setTitle(obj.getString(标题));
movie.setAuthor(obj.getString(作家));
//添加电影电影阵列
movieList.add(电影);
adapter.notifyDataSetChanged();
}赶上(JSONException E){
e.printStackTrace();
}
}
}
},新Response.ErrorListener(){
@覆盖
公共无效onErrorResponse(VolleyError错误){
VolleyLog.d(TAG,错误:+ error.getMessage());
新AlertDialog.Builder(getActivity())
.setTitle(无连接)
.setMessage(请检查你的互联网连接!)
.setPositiveButton(android.R.string.yes,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话,诠释它){
//继续进行删除
}
})
//.setNegativeButton(android.R.string.no,新DialogInterface.OnClickListener(){
//公共无效的onClick(DialogInterface对话,诠释它){
// 没做什么
//}
//})
.setIcon(android.R.drawable.ic_dialog_alert)
。显示();
hidePDialog();
}
});
。AppController.getInstance()addToRequestQueue(movieReq);
//listView.setAdapter(adapter);
}
私人查看getActionBar(){
// TODO自动生成方法存根
返回null;
}
@覆盖
公共无效的onDestroy(){
super.onDestroy();
hidePDialog();
}
私人无效hidePDialog(){
如果(pDialog!= NULL){
pDialog.dismiss();
pDialog = NULL;
}
}
}
这可能不是做的最好的方式,但它为我工作。的
您可能会有所帮助: http://www.vogella.com/tutorials/ JavaSerialization / article.html
我不得不在某些项目做。这是我做的:
公共final类cacheThis {
私人cacheThis(){}
公共静态无效的writeObject(上下文的背景下,字符串文件名,Object对象)抛出IOException异常{
FileOutputStream中FOS = context.openFileOutput(文件名,Context.MODE_PRIVATE);
ObjectOutputStream的OOS =新的ObjectOutputStream(FOS);
oos.writeObject(对象);
oos.flush();
oos.close();
fos.close();
}
公共静态对象的readObject(上下文的背景下,字符串文件名)抛出IOException异常,
ClassNotFoundException的{
的FileInputStream FIS = context.openFileInput(文件名);
ObjectInputStream的OIS =新的ObjectInputStream(FIS);
Object对象= ois.readObject();
fis.close();
返回对象;
}
}
要写入文件:
cacheThis.writeObject(YourActivity.this,文件名,movieList);
要读取文件:
movieList.addAll((名单<电影>)cacheThis.readObject(
VideoActivity.this,文件名));
您必须有你的电影类实现Serializable
I am working on a articles application like techcrunch I am parsing data from json. I am parsing title,author and image from json. Articles are displayed in list-view. I want to do offline caching means when there is no internet user can read the articles.
Here is my code-
public class OneFragment extends Fragment {
public OneFragment(){}
private static final String TAG = OneFragment.class.getSimpleName();
// Movies json url
private static String URL = "http://url";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
int current_page = 0;
int mPreLast;
SwipeRefreshLayout swipeView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.swip, container, false);
swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
swipeView.setColorScheme(android.R.color.holo_blue_dark, android.R.color.holo_blue_light, android.R.color.holo_green_light, android.R.color.holo_green_dark);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.setCancelable(false);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// TODO Auto-generated method stub
swipeView.setRefreshing(true);
Log.d("Swipe", "Refreshing Number");
( new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
swipeView.setRefreshing(false);
onStart();
}
}, 3000);
}
});
listView = (ListView) rootView.findViewById(R.id.list49);
listView.setOnScrollListener(new AbsListView.OnScrollListener()
{
@Override
public void onScrollStateChanged(AbsListView absListView, int i)
{
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount){
if (mPreLast != lastItem)
{
mPreLast = lastItem;
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading more articles...");
pDialog.show();
//pDialog.setCancelable(false);
onStart();
}
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), SingleArticle.class);
single.title = item.getTitle();
single.author = item.getAuthor();
startActivity(intent);
}
});
//pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
return rootView;
}
@Override
public void onStart(){
super.onStart();
// calling adapter changes here, just
// to avoid getactivity()null
// increment current page
current_page += 1;
// Next page request
URL = "http://url" + current_page;
//adapter = new CustomListAdapter(this, movieList);
int currentPosition = listView.getFirstVisiblePosition();
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setSelectionFromTop(currentPosition + 1, 0);
// changing action bar color
//getActivity().getActionBar().setBackground(
//new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setAuthor(obj.getString("author"));
// adding movie to movies array
movieList.add(movie);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
new AlertDialog.Builder(getActivity())
.setTitle("No Connectivity ")
.setMessage("Please check your internet connectivity!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
//.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//public void onClick(DialogInterface dialog, int which) {
// do nothing
//}
//})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
//listView.setAdapter(adapter);
}
private View getActionBar() {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
This probably isn't the best way to do it, but it worked for me.
You might find this helpful: http://www.vogella.com/tutorials/JavaSerialization/article.html
I had to do the same in some project. This is what I did:
public final class cacheThis {
private cacheThis() {}
public static void writeObject(Context context, String fileName, Object object) throws IOException {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.flush();
oos.close();
fos.close();
}
public static Object readObject(Context context, String fileName) throws IOException,
ClassNotFoundException {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
fis.close();
return object;
}
}
To write to file:
cacheThis.writeObject(YourActivity.this, fileName, movieList);
To read from file:
movieList.addAll((List<Movie>) cacheThis.readObject(
VideoActivity.this, fileName));
You have to have your Movie class implements Serializable
这篇关于在Android中如何实现JSON的离线缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!