主要记录一下安卓中几种常用的存储方式的用法。

一、SQLite

  1、创建SQLiteOpenHelper对象(当然SQLiteOpenHelper是抽象类,不能直接创建);

  2、通过上面创建的对象调用getWritableDatabase()方法获取SQLiteDatabase对象;

  3、通过SQLiteDatabase对象就可以操作数据库了。

  • 创建一个类继承自SQLiteOpenHelper

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { private final static String TABLE_NAME="sun";//表名 public DBHelper(Context context, String name, CursorFactory factory, int version) {
    super(context, name, factory, version);
    } @Override
    public void onCreate(SQLiteDatabase db) {
    String sql = "create table if not exists " + TABLE_NAME+"(id integer primary key autoincrement,sunValue varchar,Date integer)";
    db.execSQL(sql);
    } @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sql = "drop table if exists "+ TABLE_NAME;
    db.execSQL(sql);
    onCreate(db);
    } }

    注意:至少需要创建一个构造方法并调用super方法,并覆写两个方法,第一个方法onCreate创建数据库时调用,第二个方法onUpgrade版本更新时调用。

  • 这时可以创建SQLiteOpenHelper对象并调用getWritableDatabase()方法获取SQLiteDatabase对象
            DBHelper dbHelper = new DBHelper(MainActivity.this, "db_Sun.db", null, 1);
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    注意:db_Sun.db是要创建的数据库名

  • 获取到SQLiteDatabase对象就可操作数据库了,如 :插入一条数据
             String sql = "insert into sun(sunValue,Date) values('"+value+"',"+new Date().getTime()+") ";
    db.execSQL(sql);
  • 查询数据库中最新的一条数据(根据时间戳排序查询)
            Cursor c = db.rawQuery("select * from sun order by Date desc limit 1", null);
    c.moveToFirst();/*************************************/
    while (!c.isAfterLast()) {/*************************************/
    String sunValue = c.getString(c.getColumnIndex("sunValue"));
    long date = c.getLong(c.getColumnIndex("Date"));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date date2 = new Date(date); Log.i(TAG, sunValue+"--"+sdf.format(date2));
    recv_tv.setText(sunValue);
    c.moveToNext();/**************************************/
    }
    c.close();/**************************************/

二、FileSystem

  其实就是文件的读存

  1、创建File对象      java.io.File.File(File dir, String name)

  2、获取输出流/输入流

      java.io.FileOutputStream.FileOutputStream(File file, boolean append) throws FileNotFoundException

         java.io.FileInputStream.FileInputStream(File file) throws FileNotFoundException

   3、写入或读取

   4、关闭流

  • 下面是一个完整FileSystemStorage的例子(其中Context为上下文,如:MainActivity.this)

    package file;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException; import android.content.Context; public class FileOperation { private FileInputStream fis;// 输入流
    private FileOutputStream fos;// 输出流
    private final String FILENAME = "fileContent.txt";
    private Context context; public FileOperation(Context context) {
    super();
    this.context = context;
    } /**
    * 读取系统文件写入的内容
    *
    * @return
    * @throws IOException
    */
    public String readFileContent() throws IOException { String filecontent = null; File file = new File(context.getFilesDir(), FILENAME);
    fis = new FileInputStream(file); filecontent = readFis(fis); // System.out.println("readFileContent="+filecontent);
    return filecontent;
    } /**
    * 把输入流里面的内容读取到字节数组中
    *
    * @param fis
    * 输入流
    * @throws IOException
    */
    private String readFis(FileInputStream fis) throws IOException { // 定义缓冲区
    byte[] buf = new byte[1024]; int len = -1; StringBuilder sb = new StringBuilder(); // 循环读取fis中的数据
    while ((len = fis.read(buf)) != -1) {
    sb.append(new String(buf, 0, len));
    }
    // System.out.println("readFis="+sb.toString());
    return sb.toString();
    } /**
    * 读取文件的最后一行数据
    *
    * @return
    */
    public String readFisLastLine() {
    File file = new File(context.getFilesDir(), FILENAME);
    String lastLine = null;
    String buf = null;
    BufferedReader br = null;
    try {
    br = new BufferedReader(new FileReader(file));
    if (file.length() > 1024 * 1024 * 1024) {
    br.skip(file.length() / 3 * 2);//  当文件超过1M大小的时候,跳过文本长度的2/3,具体跳过多少视实际情况而定,文件越大可以跳过的部分越多
    }
    while ((buf = br.readLine()) != null && buf != "\n") {
    lastLine = buf;
    }
    br.close();
    } catch (IOException e) {
    if (br != null) {
    try {
    br.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    e.printStackTrace();
    } return lastLine;
    } /**
    * 写入文件
    *
    * @param content
    * @throws IOException
    */
    public void writeContent(String filecontent) throws IOException {
    // 通过传入的文件获得fos,默认为MODE_PRIVATE覆写
    File file = new File(context.getFilesDir(), FILENAME);
    if (false == file.exists()) {
    file.createNewFile();
    filecontent = "数据 " + "时间" + "\n" + filecontent;// 加个列名
    } fos = new FileOutputStream(file, true);// 追加
    // fos=openFileOutput(FILENAME, MODE_PRIVATE); // 向fos写入文件内容
    fos.write(filecontent.getBytes());
    // 刷新
    fos.flush(); // 关闭流,释放资源
    fos.close();
    }
    }

三、SDCardSystem

  这和filesystem差不多,只是文件位置不同

  • 文件写入方法

    /**
    * 写入内容
    */
    protected void writeContent(String content) {
    /**
    * 检查SDCard的挂载(插入)状态
    */
    String sdCardState = Environment.getExternalStorageState();
    Log.i("state", sdCardState);
    /**
    * 把获取到的sdCard状态,进行判断是否挂载
    */
    if (sdCardState.equals(Environment.MEDIA_MOUNTED)) {// SDCard已挂载
    File file = new File(Environment.getExternalStorageDirectory(), FILENAME);
    Log.i("文件路径:", Environment.getExternalStorageDirectory().getAbsolutePath());
    try {
    fos = new FileOutputStream(file);
    fos.write(content.getBytes());
    fos.flush();
    fos.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } }
    }
  • 文件读取方法
    /**
    * 读取SDCard文件的方法
    */ protected String readSdCardFile() {
    /**
    * 获取并判断SDCard挂载状态
    */
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    // SDCard已挂载
    File file = new File(Environment.getExternalStorageDirectory(), FILENAME);
    try {
    fis = new FileInputStream(file);
    content = readFis(fis);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return content;
    } private String readFis(FileInputStream fis) throws IOException {
    byte[] buf = new byte[1024];
    int len = -1;
    StringBuilder sb = new StringBuilder();
    while ((len = fis.read(buf)) != -1) {// 循环读取fis中的数据
    sb.append(new String(buf, 0, len));
    }
    // 关闭流
    fis.close(); return sb.toString();
    }

四、SharedPreferences(喜好.xml文件存储)

  SharedPreferences文件是一个xml文件,保存的是键值对(key-value)。

  1、通过上下文SharedPreferences对象;

  2、获取Editor;

  3、put值;

  4、提交。

  • 完整的存储读取类

    package file;
    
    import java.util.Map;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor; public class FileOperation { private final String SPNAME = "fileContent";// 喜好文件名
    private Context context;
    private SharedPreferences sp; public FileOperation(Context context) {
    super();
    this.context = context;
    } /**
    * 读取系统文件写入的内容(这里读取最后一条)
    * @return
    */
    public String readFileContent() {
    sp = context.getSharedPreferences(SPNAME, Context.MODE_PRIVATE);
    // sp.getString(key, defValue);//通过key获取一个value Map<String, ?> map = sp.getAll();
    /* for (Entry<String, String> entry : map.entrySet()) {//遍历所有的key-value System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } */ String lastKey = null;
    String lastValue = null;
    for (String key : map.keySet()) {//遍历所有的Key,得到最后一个key
    lastKey = key;
    }
    if (null != lastKey) {
    lastValue = (String) map.get(lastKey);//获取最后一个value
    // lastValue = sp.getString(lastKey, "");
    }
    return lastValue; } /**
    * 写入文件
    *
    */
    public void writeContent(String key,String value) {
    /*
    * sp=MainActivity.this.getPreferences(mode);
    * 这种方式获取的喜好文件一个Activity有且仅有一个 原因是:它得到的喜好文件的文件名为这个Activity的类名
    */ // 通过上下文获取sp
    sp = context.getSharedPreferences(SPNAME, Context.MODE_PRIVATE);
    // 获取editor
    Editor editor=sp.edit();
    //放入键值对
    editor.putString(key, value); //注意:放入键值对后一定要提交
    editor.commit();
    }
    }

小结:

SQLite、FileSystem、SharedPreferences方式的文件储存的位置都在根目录下data目录下的data目录下的当前包名下:/data/data/com.yyc.test/...

SDCardSystem方式的存储位置在sd卡中(我手机没有sd卡,不知道为什么直接在根目录下,欢迎右上角QQ交流)

Android的四种储存方式(SQLite、FileSystem、SDCardSystem、SharedPreferences)的更多相关文章

  1. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (二) —— SQLite

    SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是: NULL: 空值 INTEGER: 整数 REAL: 浮点数 TEXT: 字符串 BLOB: 大数据 在SQLite中, ...

  2. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (一) —— 总览

    Android数据的四种存储方式SharedPreferences.SQLite.Content Provider和File (一) —— 总览   作为一个完成的应用程序,数据存储操作是必不可少的. ...

  3. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences

    除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息.其存储位置在/data ...

  4. Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (四) —— ContentProvider

    ContentProvider是安卓平台中,在不同应用程序之间实现数据共享的一种机制.一个应用程序如果需要让别的程序可以操作自己的数据,即可采用这种机制.并且此种方式忽略了底层的数据存储实现,Cont ...

  5. (转)Android数据的四种存储方式SharedPreferences、SQLite、Content Provider和File (三) —— SharePreferences

    除了SQLite数据库外,SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息.其存储位置在/data ...

  6. [Android]Android数据的四种存储方式

    存储方式 Android提供以下四种存储方式: SharePreference SQLite File ContentProvider Android系统中数据基本都是私有的,一般存放在“data/d ...

  7. [转][Android]Android数据的四种存储方式

    android.database.sqlite类 SQLiteQueryBuilder java.lang.Object android.database.sqlite.SQLiteQueryBuil ...

  8. Android开发之基本控件和详解四种布局方式

    Android中的控件的使用方式和iOS中控件的使用方式基本相同,都是事件驱动.给控件添加事件也有接口回调和委托代理的方式.今天这篇博客就总结一下Android中常用的基本控件以及布局方式.说到布局方 ...

  9. Android下的数据储存方式( 二)

    在上一篇文章中我们介绍了SharedPreferences的使用方法. 今天我们继续介绍另一种储存数据的方式:使用内部储存和外部储存 每一个Android设备都拥有两个数据储存区域:外部储存和外部储存 ...

随机推荐

  1. org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x160fd6f04410017 after 0ms

    dubbo报错: org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x160fd6f04410017 after ...

  2. Post And Get接口测试

    public class TestPost {   public static String do_post(String url, Map<String, String> params) ...

  3. Centos7 下Boost 1.61.0源码 配置开发环境

    1 下载地址 https://sourceforge.net/projects/boost/files/boost/1.61.0/ boost_1_61_0.tar.gz 2 卸载系统自带的boost ...

  4. Druid对数据库密码加密的坑

    背景: 在对已有项目搭建本地环境,修改了本地ip端口和数据库帐号密码(使用了明文). 然后项目一直跑不起来,还抛出各种异常,经过分析发现主要错在这里:druid java.lang.IllegalAr ...

  5. python的进程与线程

    一.进程与线程的相关概念 1.什么是进程 进程是一个程序在一个数据集上的一次动态执行过程. 进程一般由程序,数据集,进程控制块三部分组成. 2.什么是线程 线程也叫轻量级进程,它是一个基本的CPU执行 ...

  6. 模块 - logging/re

    logging 模块 很多程序都有记录日志的需求 logging的日志可以分为 debug(), info(), warning(), error() and critical()5个级别 1.最简单 ...

  7. BaseDao 接口

    // 以后所有的 Dao 接口都需要继承 BaseDao 接口; // 自定义泛型接口 public interface BaseDao<T>{ public void save(T t) ...

  8. HttpSession 入门

    1. HttpSession 概述 位于 javax.servlet.http 包; HttpSession 是由 JavaWeb 提供的功能, 用来会话跟踪的类, session 是服务器端对象, ...

  9. python2 一些错误处理

    python2各种问题 pip安装django出错:python2 -m pip install django 编码问题:Unicode Decode Error ascii codec can't ...

  10. 用仿ActionScript的语法来编写html5——第六篇,TextField与输入框

    一,对比1,html5中首先看看在html5的canvas中的文字显示 var canvas = document.getElementById("myCanvas"); var ...