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

  • 相关阅读:
    【转】Eclipse插件开发之基础篇(1) 插件开发的基础知识
    js获取周.html
    Go语言 基础
    MySQL replace into
    元认知:思考“何为思考”
    redis 流水线
    关于Blog现象的一些思考。
    [LCS]LCS2005服务器应用程序
    [WAP]dotNet在WAP应用开发中实现按指定页数翻页的解决方案
    [Cache]深入学习Enterprise Library for .NET Framework 2.0的Cache机制——分析篇
  • 原文地址:https://www.cnblogs.com/Draymonder/p/9842991.html
Copyright © 2011-2022 走看看