• 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:运行结果。

  • 相关阅读:
    centos 7:network: 正在打开接口 ens33: 错误:激活连接失败:No suitable device found for this connection.
    python 连接 hive 的 HiveServer2 的配置坑
    node的 node-sass@^4.11.0 出现:npm: no such file or directory, scandir '.../node_modules/node-sass/vendor'
    DX关联VS
    PIX
    英特尔® 图形性能分析器(Intel® GPA)
    C++之异常处理
    VS挂接崩溃包
    system 函数
    C++ Template
  • 原文地址:https://www.cnblogs.com/yshyee/p/3368518.html
Copyright © 2020-2023  润新知