android資料持久化儲存

來源:互聯網
上載者:User

標籤:int   upd   iter   end   exe   string   tde   line   alt   

一、檔案儲存體

  資料存放區到檔案中:

  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儲存(即使用“索引值對”的方式儲存資料)

  儲存資料步驟:

    1、首先擷取SharedPreferences對象

      

      三種方式擷取:

        第一種:Context類中的getSharedPreferences()方法;

        第二種:Activity類中的get Preferences()方法;

        第三種:Preferences類中的getDefaultSharedPreferences()方法。

 

    2、然後向SharedPreferences檔案儲存體資料

      分三步:

        (1)調用SharedPreferences對象的edit()方法來擷取一個SharedPreferences.Editor對象;

        (2)向SharedPreferences.Editor對象中添加資料;

        (3)調用apply()方法將添加資料提交。

                 如:

        Shared Preferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();

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

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

        editor.apply();

 

  讀取資料步驟:

    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);

                         }

      }

 

     

 

     

 

 

 

 

 

 

 

 

 

 

 

      

android資料持久化儲存

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.