Android 将从网络获取的数据缓存到私有文件
1:activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"> <Button
android:id="@+id/btn_get_titles"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Titles"/> <ListView
android:id="@+id/lv_show"
android:layout_below="@id/btn_get_titles"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
2:MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
private Button btnGetTitles=null;
private ListView lvShow=null;
private List<String> titleList=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); initUI(); btnGetTitles.setOnClickListener(this);
} private void initUI(){
btnGetTitles=(Button)findViewById(R.id.btn_get_titles);
lvShow=(ListView)findViewById(R.id.lv_show);
} @Override
public void onClick(View arg0) {
new Thread(new GetTitlesThread()).start();
} Handler getTitlesHandler=new Handler(){
public void handleMessage(Message msg){
if(msg.what==100){
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_list_item_1,
titleList);
lvShow.setAdapter(adapter);
}
}
};
class GetTitlesThread implements Runnable{
@Override
public void run() {
//1:判断缓存文件是否存在。/data/data/com.yan.example/jsontest/files/titles.txt
String path=getFilesDir().getPath()+"//" ;
File file=new File(path+"titles.txt");
if(file.exists()){
//2:如果缓存文件存在,就从文件取数据。
readFile("titles.txt");
getTitlesHandler.obtainMessage(100).sendToTarget();
}else{
//3:如果缓存文件不存在,就从网络取数据 ,然后将数据保存到缓存文件。
String url="http://www.zhihuiqd.com/wsht/server/selectTitle2json.php";
String res=getStringFromeNet(url); saveFile("titles.txt",res);//////将内容缓存起来 try{
JSONArray json=new JSONArray(res);
int len=json.length();
String title="";
titleList=new ArrayList<String>(); for(int i=0;i<len;i++){
JSONObject temp=(JSONObject)json.get(i);
title=temp.getString("title");
titleList.add(title);
}
}catch(Exception e){
e.printStackTrace();
}
getTitlesHandler.obtainMessage(100).sendToTarget();
}
}
} //保存文件
private void saveFile(String filename,String str){
try{
FileOutputStream fos=openFileOutput(filename,Activity.MODE_PRIVATE);
byte[]bytes=str.getBytes();
fos.write(bytes);
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
} //读取文件
private void readFile(String filename){
String res="";
try{
FileInputStream fis=openFileInput(filename);
int length=fis.available();
byte[]buffer=new byte[length];
fis.read(buffer);
res=EncodingUtils.getString(buffer, "UTF-8");
fis.close();
JSONArray json=new JSONArray(res);
int len=json.length();
String title="";
titleList=new ArrayList<String>();
for(int i=0;i<len;i++){
JSONObject temp=(JSONObject)json.get(i);
title=temp.getString("title");
titleList.add(title);
}
}catch(Exception e){
e.printStackTrace();
}
} //从网络服务端取数据
private String getStringFromeNet(String url){
StringBuilder builder=new StringBuilder();
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(url);
try{
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==200){
BufferedReader reader=new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
for(String s=reader.readLine();s!=null;s=reader.readLine()){
builder.append(s);
}
}
}catch(Exception e){
e.printStackTrace();
}
return builder.toString();
}
}
3:运行结果。
Android 将从网络获取的数据缓存到私有文件的更多相关文章
- Android LazyList 从网络获取图片并缓存
原演示地址 本文内容 环境 演示 LazyList 从网络获取图片并缓存 参考资料 本文是 Github 上的一个演示,通过网络获取歌手专辑的缩略图,并显示在 ListView 控件中.该演示具备将缩 ...
- Android 把从网络获取的图片缓存到内存中
1:activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi ...
- Android Volley 库通过网络获取 JSON 数据
本文内容 什么是 Volley 库 Volley 能做什么 Volley 架构 环境 演示 Volley 库通过网络获取 JSON 数据 参考资料 Android 关于网络操作一般都会介绍 HttpC ...
- Android开发——获取应用数据/缓存大小并清理缓存
1. 获取应用数据/缓存大小 其中pm为实例化的PackageManager,因为需要遍历所有的已安装的应用.因此需要开启子线程进行处理. 还有需要注意的是,在Android4.2之前getPacka ...
- (转载)Android之三种网络请求解析数据(最佳案例)
[置顶] Android之三种网络请求解析数据(最佳案例) 2016-07-25 18:02 4725人阅读 评论(0) 收藏 举报 分类: Gson.Gson解析(1) 版权声明:本文为博主原创 ...
- Android热身:通过网络获取资源并更新UI组件
Android热身:通过网络获取资源并更新UI组件 目标 点击"发送请求"按钮,下载某网页的html源码,并显示在TextView控件上:点击"清空",清除Te ...
- android客户端从服务器端获取json数据并解析的实现代码
今天总结一下android客户端从服务器端获取json数据的实现代码,需要的朋友可以参考下 首先客户端从服务器端获取json数据 1.利用HttpUrlConnection /** * 从指定的U ...
- (转)android客户端从服务器端获取json数据并解析的实现代码
今天总结一下android客户端从服务器端获取json数据的实现代码,需要的朋友可以参考下 首先客户端从服务器端获取json数据 1.利用HttpUrlConnection 复制代码 ...
- Android之三种网络请求解析数据(最佳案例)
AsyncTask解析数据 AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法. ...
随机推荐
- webex录屏
你在寻找好用的录屏软件吗?商用级品质的 WebEx Recorder 就是一款优秀的录屏软件.WebEx Recorder可以录制全屏或指定窗口,可以设定是否包含声音,生成的文件体积极小且极清晰,录制 ...
- windows 编程—— 学习指导
这里有一份很好的资源,被制作成chm文件的<Windows 程序设计>,包含了中文版和英文版,还有全书源代码,虽然不知道是谁出版的,但是感觉对Windows编程新手来说还是很不错的.关键还 ...
- PHP常用封装类
1.mysql.class.php <?php // namespace Package; /** * MySQL 类 * @author cxm <tsai.er6@gmail.com& ...
- javascript 判断是否是数组
function isArray(object){ return object && typeof object==='object' && typeof object ...
- postgres中的merge join
目前数据库中的join操作 无非三种 nextloop merge hash 本文分析pg的merge join 不得不说pg真是学习数据库实现的好东西 不愧是学院派 用来教学的 代码写的干净注释清晰 ...
- WPS2012交叉引用技巧,word比wps这点强更新參考文献
WPS2012交叉引用技巧,word比wps这点强更新參考文献 到时生成仅仅有有一条线,好像WPS不能够,word能够,假设谁知道能够补充.^_^ 1.写论文,參考文献的改动非 ...
- [ES6] Converting an array-like object into an Array with Array.from()
Array.from() lets you convert an "iterable" object (AKA an array-like object) to an array. ...
- shell 判断文件、目录是否存在
shell判断文件是否存在 1. shell判断文件,目录是否存在或者具有权限 2. #!/bin/sh 3. 4. myPath="/var/log/httpd/" 5. m ...
- [转] The Single Biggest Obstacle to Trading Success
Why do some people succeed spectacularly in the market while others fail? The market is the same for ...
- cogs 线型网络(状压dp)
/* 需要好大的空间..... 而且lowbit理解的不是很好 先放到博客里 以后慢慢研究 */ #include<iostream> #include<cstdio> #in ...