android数据持久化存储

一、文件存储

  数据存储到文件中:

  public void save(){

    String data = "Data to save";

    FileOutputStream out = null;

    BufferedWriter writer = null;

    try{

      out = openFileOutput("data",Context.MODE_PRIVATE);

      /*

           openFileOutput用于将数据存储到指定文件中,返回的out是一个FileOutputStream对象(字节流),其中第一个

                 参数指文件名,第二个参数指文件操作模式,有两种:

                        MODE_PRIVATE是默认操作模式,表示指定同样文件名时,所写入的内容将会覆盖原文件中的内容;

                        MODE_APPEND表示如果该文件存在,就往文件里追加内容,不存在就建立新文件.

      */

       writer = new BufferedWriter(new OutputStreamWriter(out));

       writer.write(data);

    }catch(IOExption e){

      e.printStackTrace();

    }finally{

      

      try{

        if(writer != null){

           writer.close();

                        }

      }catch(IOExption e){

        e.printStackTrace();

    }

  }

  数据从文件中读取:

  public String load(){

    FileInputStream in = null;

    BufferedReader reader = null;

    StringBuilder content = new StringBuilder();

    try{

      in = openFileInput("data");

      reader = new BufferedReader(new FileInputReader(in));

      String line = "";

      While((line = reader.readerLine()) != null){

        content.append(line);

      }

    }catch(IOException e){

      e.printStackTrace();

    }finally{

      if(reader != null){

        try{

          reader.close();

        }catch(IOException e){

          e.printStackTrace();

        }

      }

    }

    return content.toString();

  }



二、SharedPreferences存储(即轻型的数据存储方式,本质是使用XML文件存储“键值对”数据)

  存储数据步骤:

    1、首先获取SharedPreferences对象

      

      三种方式获取:

        第一种:Context类中的getSharedPreferences()方法(一般用这个);

        第二种:Activity类中的getPreferences()方法;

        第三种:Preferences类中的getDefaultSharedPreferences()方法。

    2、然后向SharedPreferences文件存储数据

      分三步:

        (1)调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象;

        (2)向SharedPreferences.Editor对象中添加数据;

        (3)调用apply()方法将添加数据提交。

                 如:

  Shared Preferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();//"data"表示当前SharedPreferences文件的名字,MODE_PRIVATE指模式

  editor.putString("name","Qbin");

  editor.putString("age","25");

  editor.apply();

               SharedPreferences对象本身只能获取数据而不支持存储和修改,存储和修改是通过Editor对象实现。 

  读取数据步骤:

    1、首先获取SharedPreferences对象;

    2、用SharedPreferences对象中一系列get方法,对存储的数据进行读取。

     如:

         SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);

       String name = pref.getString("name","");

                     Int age = pref.getInt("age",0);



三、SQLite数据存储(需要借助SQLiteOpenHelper抽象类)

  

 SQLiteOpenHelper抽象类:

    有2个构造方法:一般用其中参数最少也是最常用的构造方法 ( 第一个参数Context,第二个参数数据库名,第三个参数是Cursor一般传入null即可,第四个参数是数据库

           版本号 );

    有2个抽象方法:分别是onCreate()和onUpgrade();

            

    有2个实例方法:分别是getReadableDatabase()和getWritableDatabase();

          

                    

    如:

      创建数据库:

      public class MyDatabaseHelper extends SQLiteHelper{

           public static final String CREATE_BOOK = "create table Book("

                       +"id integer primary key autoincrement,"

                       +"author text,"

                       +"price real,"

                       +"pages integer,"

                       +"neme text)";  

          //建表语句,其中integer表示整形,real表示浮点型,text表示文本

          private Context mContext;

          public MyDatabaseHelper(Context context , String name , SQLiteDatabase.CursorFactory factory , int version ){

            super(context , name , factory , version);

            mContext = context;

         }

          public void onCreate(SQLiteDatabase db){

                         db.execSQL(CREATE_BOOK); 

          //  execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;

          //rawQuery()方法可以执行select语句。

          Toast.makeText(mContext , "Create succeeded", Toast.LENGTH_SHORT).show();

          }

 

         public void onUpgrade(SQLiteDatabase db , int oldVersion , int newVersion){

                         }

      }

    

              升级数据库(针对上面的数据库进行升级,比如:除了BOOK表之外再添加一张Category表):

      public class MyDatabaseHelper extends SQLiteHelper{

           public static final String CREATE_BOOK = "create table Book("

                       +"id integer primary key autoincrement,"

                       +"author text,"

                       +"price real,"

                       +"pages integer,"

                       +"neme text)";  

      public static final String CREATE_CATEGORY = "create table Category("

           +"id integer primary key autoincrement,"

           +"category_name text,"

           +"category_code integer)";

          private Context mContext;

          public MyDatabaseHelper(Context context , String name , SQLiteDatabase.CursorFactory factory , int version ){

            super(context , name , factory , version);

            mContext = context;

         }

          public void onCreate(SQLiteDatabase db){

                         db.execSQL(CREATE_BOOK); 

         db.execSQL(CREATE_CATEGORY);

           Toast.makeText(mContext , ”Create succeeded” , Toast.LENGTH_SHORT).show();

          }

         public void onUpgrade(SQLiteDatabase db , int oldVersion , int newVersion){

            db.execSQL(CREATE_BOOK); 

          db.execSQL(CREATE_CATEGORY);

        onCreate(db);

                         }

      }

四、LitePal操作数据库

LitePal采用对象关系映射(ORM)模式,使用文档 https://github.com/LitePalFramework/LitePal

   使用LitePal可以简化对SQLite的操作(不用使用SQL语句)

 

 

     

      

原文地址:https://www.cnblogs.com/qianbin/p/8393978.html