Android 数据存储方案

来源:互联网 发布:如何安装ubuntu 16.04 编辑:程序博客网 时间:2024/04/28 04:08

Android系统中主要提供了三种方式用于简单地实现数据持久化功能:即文件存储、SharedPreference存储以及数据库存储。

一、文件存储

Context类提供了一个 openFileOutputStream()方法,用于将数据存储到指定的文件中。该方法有两个参数,第一个参数为要创建的文件名,注意文件名不包括路径,默认放在 /data/data//files/目录下,第二个参数为操作模式, MODE_ PRIVATE 为默认操作模式,表示创建的文件名同名时,会覆盖原文件中的内容.MODE_ PRIVATE 表示创建的文件名同名时会在原文后追加内容。
openFileOutput()方法返回的是一个FileOutputStream对象。

下面是FilePersistence工程实例:

//MainActivity文件package com.example.filepersistencetest;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.text.TextUtils;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {    private EditText edit;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        edit=(EditText)findViewById(R.id.edit);        String inputText =load();        if(!TextUtils.isEmpty(inputText)){ //TextUilts.isEmpty() 判断是否为空            edit.setText(inputText);            edit.extendSelection(inputText.length());            Toast.makeText(this,"Restoring successed ", Toast.LENGTH_SHORT).show();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        String inputText = edit.getText().toString();        save(inputText);    }    public void save(String inputText){        FileOutputStream out = null;        BufferedWriter writer = null;        try{            out =openFileOutput("data", Context.MODE_PRIVATE);            writer=new BufferedWriter(new OutputStreamWriter(out));            writer.write(inputText);        }catch(IOException e){            e.printStackTrace();        }finally{            try{                if(writer!=null){                    writer.close();                }            }catch(IOException e){                e.printStackTrace();            }        }    }    public String load(){        FileInputStream in = null;        BufferedReader reader = null;        StringBuilder content = new StringBuilder();        try{            in = openFileInput("data");            reader = new BufferedReader(new InputStreamReader(in));            String line = "";            while((line=reader.readLine())!=null){                content.append(line);            }        }catch(IOException e){            e.printStackTrace();        }finally{            if(reader!=null){                try{                    reader.close();                }catch(IOException e){                    e.printStackTrace();                }            }        }        return content.toString();    }}

布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <EditText        android:id="@+id/edit"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="type something here" /></LinearLayout>

二、SharedPreference存储

SharedPreference 支持将不同类型的数据以键值对形式存储在xml文件中

三、SQLite数据库存储

Android为了让我们能够更加方便地管理数据库,专门提供了SQLiteOpenHelper帮助类,可以非常简单地对数据库进行创建和升级。其中SQLiteOpenHelper是一个抽象类,需要创建一个自己的帮助类去继承它。其中有两个抽象方法,分别是
onCreate() 和onUpgarde(),需要我们自己去重写,然后在这两个方法中去实现创建、升级数据库的逻辑。
SQLIteOpenHelper中还有两个非常重要的实例方法,getReadableDatabase()和getWritableDatabase().这两个方法用于创建和打开一个现有的数据库(如果数据库存在则直接打开,否者创建一个新的数据库),并返回一个可对数据库进行读写操作的对象。
SQLIteOpenHelper中有两个构造方法可重写,一般使用参数少的那个构造方法。这个方法有四个参数,第一个参数是Context,第二个参数是数据名,第三个参数是我们查询数据库时候返回一个定义的Cursor,一般都是传入null.第四个参数表示当前数据库的版本号,可用于对数据库进行升级操作。调用getReadableDatabase()或者getWritabledataBase()方法就能够创建数据库了,数据库文件会放在/data/data//databases/目录下,这时onCreate方法也会得到执行,所以通常会在这里去处理一些创建表的逻辑。

1、对数据库的增删改查

//MyDatabaseHelpe.java文件package com.example.databasetest;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;import android.widget.Toast;public class MyDatabaseHelper extends SQLiteOpenHelper {    public static final String CREATE_BOOK ="create table Book ("               +"id integer primary key autoincrement,"               +"author text, "               +"price real, "               +"pages integer, "               +"name 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, CursorFactory factory, int version) {        super(context, name, factory, version);        mContext = context;    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(CREATE_BOOK);        db.execSQL(CREATE_CATEGORY);        Toast.makeText(mContext,"Create succeeded",Toast.LENGTH_LONG).show();    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        db.execSQL("drop table if exists book");        db.execSQL("drop table if exists Category");        onCreate(db);    }}
//MainActivity.javapackage com.example.databasetest;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {    private MyDatabaseHelper   dbHelper;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        dbHelper=new MyDatabaseHelper(this,"BookStore.db", null,2);        Button createDatabase =(Button)findViewById(R.id.create_database);        createDatabase.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                dbHelper.getWritableDatabase();            }        });        Button addData =(Button)findViewById(R.id.add_data);        addData.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                SQLiteDatabase db = dbHelper.getWritableDatabase();                ContentValues values =  new ContentValues();                values.put("name","The Da Vinci Code");                values.put("author","Dan Brown");                values.put("pages",454);                values.put("price",16.96);                db.insert("Book",null,values);                values.clear();//清除之前的数据                values.put("name","The Lost Symbol");                values.put("author","Dan Brown");                values.put("pages",510);                values.put("price",19.95);                db.insert("Book",null, values);            }        });        Button updateData = (Button) findViewById(R.id.update_data);        updateData.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                SQLiteDatabase db = dbHelper.getWritableDatabase();                ContentValues values = new ContentValues();                values.put("price", 10.9);                db.update("Book", values,"name=?",new String[]{"The Da Vinci Code"});            }        });        Button deleteData =(Button) findViewById(R.id.delete_data);        deleteData.setOnClickListener( new OnClickListener() {            @Override            public void onClick(View v) {               SQLiteDatabase db =dbHelper.getWritableDatabase();               db.delete("Book","pages > ?", new String [] {"500"});            }        });       Button quaryData =(Button) findViewById(R.id.quary_data);       quaryData.setOnClickListener( new OnClickListener() {        @Override        public void onClick(View v) {              SQLiteDatabase db =dbHelper.getWritableDatabase();              Cursor cursor =db.query("Book", null, null, null, null, null, null);              if(cursor.moveToFirst()){                 do{                     String name = cursor.getString(cursor.getColumnIndex("name"));                     String author = cursor.getString(cursor.getColumnIndex("author"));                     int pages = cursor.getInt(cursor.getColumnIndex("pages"));                     double price = cursor.getDouble(cursor.getColumnIndex("price"));                     Log.d("MainActivity","book name is "+name);                     Log.d("MainActivity","book author is "+author);                     Log.d("MainActivity","book pages is "+pages);                     Log.d("MainActivity","book price is "+ price);                 }while(cursor.moveToNext());               }              cursor.close();        }    });        }}

布局文件

//activity_main.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button        android:id="@+id/create_database"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Create database" />    <Button        android:id="@+id/add_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Add Data" />    <Button        android:id="@+id/update_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Update_Data" />    <Button        android:id="@+id/delete_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Delete_Data" />    <Button        android:id="@+id/quary_data"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Quary_data" /></LinearLayout>

2、使用SQL语句完成对数据库的操作

db.execSQL("insert into Book (name,author,pages,price) values(?,?,?,?)",new String[]{ "The Da vinci Code","Dan Brown","454","16.96"});

3、使用事务

       Button replaceData =(Button)findViewById(R.id.replace_data);       replaceData.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View v) {            SQLiteDatabase db = dbHelper.getReadableDatabase();            db.beginTransaction();//开启事务            try{                db.delete("Book", null, null);                if(true){                    throw new NullPointerException();                }                ContentValues values = new ContentValues();                values.put("name","Game of Thrones");                values.put("author","George Martin");                values.put("pages", 720);                values.put("price", 20.85);                db.insert("Book", null, values);                db.setTransactionSuccessful();//事务已经执行成功            }catch(Exception e){                e.printStackTrace();            }finally {                db.endTransaction();//结束事务            }        }    });    }
0 0
原创粉丝点击