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

  • 相关阅读:
    【nginx】ubuntu 安装最新版本nginx
    【Linux】dpkg: error processing package XXX (configure) 解决方法
    Ubuntu 搭建文件服务器 (wget 浏览器均可下载)
    GitStats 统计Git所有提交记录工具
    Effective C++ 笔记 —— Item 51: Adhere to convention when writing new and delete.
    Effective C++ 笔记 —— Item 53: Pay attention to compiler warnings.
    Effective C++ 笔记 —— Item 50: Understand when it makes sense to replace new and delete.
    Effective C++ 笔记 —— Item 47: Use traits classes for information about types.
    Effective C++ 笔记 —— Item 45: Use member function templates to accept "all compatible types."
    Effective C++ 笔记 —— Item 46: Define nonmember functions inside templates when type conversions are desired.
  • 原文地址:https://www.cnblogs.com/yshyee/p/3368518.html
Copyright © 2020-2023  润新知