zoukankan      html  css  js  c++  java
  • 安卓开发 数据存储

    数据存储方式

      文件存储 提供openFileInput() 和 openFileOutput()

      SharedPreferences 存储应用程序的各种配置信息

      SQLite 

      ContentProvider 安卓四大组件之一,用于应用程序之间的数据交换

      网络存储 将数据存储到服务器上,通过网络提供的存储空间来 存储/获取 数据信息

    文件存储

      output

    String fileName = "data.txt";
    String content = "hello world";
    try {
        FileOutputStream fos = this.openFileOutput(fileName, MODE_APPEND);
        fos.write(content.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

      input

    String content = null;
    FileInputStream fis;
    try {
        fis = this.openFileInput("data.txt");
        byte []buffer = new byte[fis.available()];
        fis.read(buffer);
        content = new String(buffer);
        Log.i("data.txt",content);
        fis.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    外部存储

      如若程序需要访问关键信息,必须在清单文件中声明权限

    XML 解析

      DOM解析

      SAX解析

      PULL解析

    JSON解析

      json数组只有 json对象和 json数组

      json对象解析

    XmlPullParser parser = Xml.newPullParser();
    String content = "{"name":"draymonder", "age":20 ,"married":false}";
    try {
        JSONObject jsonObj = new JSONObject(content);
        String name = jsonObj.optString("name");
        int age = jsonObj.optInt("age");
        boolean married = jsonObj.optBoolean("married");
        Log.i("Main1",name + " " + age + " " + married);
    } catch (JSONException e) {
        e.printStackTrace();
    }

      json数组解析

    String arrcontent = "[16,2,26]";
    
    try {
        JSONArray jsonArray = new JSONArray(arrcontent);
        for(int i=0; i<jsonArray.length(); i++) {
            int age = jsonArray.optInt(i);
            Log.i("MAIN", Integer.toString(age));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

      Gson 也可以解析 ,暂时就不写了

     SharedPreferences

      也是简单的一种键值映射关系。需要使用的时候就用Shared Preferences.Editor

  • 相关阅读:
    Python-内存管理
    Python如何操作Excel
    336. 文本压缩
    Python-锁
    MVC接收以post形式传输的各种参数
    linux批量替换指定文件夹中所有文件的指定内容
    ES6:string.raw浅析
    node学习笔记
    运行node提示:events.js:160 throw er; // Unhandled 'error' event
    socket.io入门示例参考
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9842991.html
Copyright © 2011-2022 走看看