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

  • 相关阅读:
    css 垂直居中
    pdf.js 标题修改
    electron 打包时文件复制到程序目录下
    js 高阶函数
    计算一个数字是否素数
    Object.assign()
    vue 路由页面 首次打开浏览器 返回上一页异常问题
    swagger使用报错:No enum constant org.springframework.web.bind.annotation.RequestMethod.get
    idea 关于查询的快捷键
    域渗透之CrackMapExec
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9842991.html
Copyright © 2011-2022 走看看