Android--数据储存

1.文件储存

文件储存数据

  • 通过openFileOutput()方法创建一个FileOutputStream对象:
FileOutputStream out = null;
out = openFileOutput( "data", Context.MODE_PRIVATE );
  • 借助FileOutputStream对象创建一个OutputStreamWriter对象
  • 使用OutputStreamWriter对象创建一个BufferedWriter对象:
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(out));
  • 通过BufferedWriter对象的write()方法写入数据:
writer.write(inputText);
  • 关闭:
writer.close();
  • eg:
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();
        }
    }
}

文件读取数据

  • 通过openFileInput()方法创建一个FileInputStream对象:
FileInputStream in = null;
in = openFileInput( "data" );
  • 借助FileInputStream对象创建一个InputStreamReader对象
  • 通过InputStreamReader对象创建一个BufferedReader对象:
BufferedReader reader = null;
reader = new BufferedReader( new InputStreamReader(in) );
  • 读取数据:
String line = "";
//将数据写入content对象
while ((line = reader.readLine()) != null){
    content.append( line );
}
//将content对象return出去
return content.toString();
  • 5.关闭:
reader.close();
  • eg
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();
}

2. SharedPreferences储存

SharedPreferences储存数据
1.调用SharedPreferences对象的edit()方法创建一个SharedPreferences.Editor对象

SharedPreferences.Editor editor = getSharedPreferences( "data2",MODE_PRIVATE ).edit();

2.写入数据

editor.putString( "name","Sim" );
editor.putInt( "age",22 );
editor.putBoolean( "married",false );

3.提交

editor.commit();

eg

//button事件通过SharedPreferences方法储存数据到文件
saveData_button.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View view) { 
        SharedPreferences.Editor editor = getSharedPreferences( "data2",MODE_PRIVATE ).edit();
        editor.putString( "name","Sim" );
        editor.putInt( "age",22 );
        editor.putBoolean( "married",false );
        editor.commit();
        Toast.makeText( MainActivity.this,"已通过SharedPreferences存储数据", Toast.LENGTH_SHORT ).show();
    }
} );

SharedPreferences读取数据
1.调用SharedPreferences对象的edit()方法创建一个SharedPreferences.Editor对象

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

2.读取数据

String name = pref.getString( "name","" );
int age = pref.getInt( "age",0 );
boolean married = pref.getBoolean( "married",false );

eg

//button事件通过SharedPreferences方法从文件读取数据
readData_button.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View view) { 
        SharedPreferences pref = getSharedPreferences( "data2",MODE_PRIVATE ); 
        String name = pref.getString( "name","" );
        int age = pref.getInt( "age",0 );
        boolean married = pref.getBoolean( "married",false ); 
    }
} );

3. SQLite数据库储存

创建数据库和建表操作

  • 新建一个类继承SQLiteOpenHelper。里面编写创建、更新数据库的SQL语句
public class MyDatabaseHelper extends SQLiteOpenHelper {
    //将SQL建表语句定义成一个常量
    public static final String CREATE_BOOK = "create table Book("
            + "id integer primary key autoincrement,"
            + "author text,"
            + "price real,"
            + "pages integer,"
            + "name text)";
    private Context mcontext;

    public MyDatabaseHelper(Context context, String name,SQLiteDatabase.CursorFactory factory, int version) {
        super( context, name, factory, version );
        mcontext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
       //建表
       db.execSQL( CREATE_BOOK );
       Toast.makeText( mcontext,"已创建数据库表",Toast.LENGTH_SHORT ).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //如果已经存在Book或Category表,则删除两张表,调用onCreate()方法重新建表
        db.execSQL( "drop table if exists Book" ); 
        onCreate( db );
    }
}
  • 构建这个类的对象调用构造方法创建数据库
//构建一个MyDatabaseHelper对象(数据库名为BookStoredb.db,版本号为1)
dbHelper = new MyDatabaseHelper( this,"BookStore.db",null,1 );

添加数据

  • 获取SQLiteDatabase对象
SQLiteDatabase db = dbHelper.getWritableDatabase();
  • 实例化一个ContentValues用来装载待插入的数据
ContentValues values = new ContentValues(  );
  • 添加数据到ContentValues对象中
values.put( "name","Hello Sim" );
values.put( "author","Dan Brown" );
values.put( "pages",454 );
values.put( "price",16.96 );
  • 调用insert()方法将ContentValues对象添加到表中
db.insert( "Book",null,values );

修改数据

  • 获取SQLiteDatabase对象
SQLiteDatabase db = dbHelper.getWritableDatabase();
  • 实例化一个ContentValues用来装载待插入的数据
ContentValues values = new ContentValues(  );
  • 给ContentValues对象指定一组数据
values.put( "price",10.96 );
  • 调用insert()方法将ContentValues对象添加到表中
db.update( "Book",values,"name=?",new String[]{"Hello Sim"} );
//将Book表里名字是Hello Sim的这本书价格改成10.96

删除数据

  • 获取SQLiteDatabase对象
SQLiteDatabase db = dbHelper.getWritableDatabase();
  • 调用delete()方法删除数据
db.delete( "Book","pages>?",new String[]{"500"} );
//将Book表里pages值大于500的数据

查询数据

  • 获取SQLiteDatabase对象
SQLiteDatabase db = dbHelper.getWritableDatabase();
  • 调用query()方法查询数据
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.e( "Query", "book name is"+name  );
        Log.e( "Query", "book author is"+author  );
        Log.e( "Query", "book pages is"+pages  );
        Log.e( "Query", "book price is"+price  );
    }while (cursor.moveToNext());
}
cursor.close();

4.内容提供器

自定义内容提供器
新建一个继承自 ContentProvider 的类,实现它的 6 个抽象方法:
onCreate(),getType(),insert(),delete(),update(),query()
Android--数据储存_第1张图片

你可能感兴趣的:(Android开发,android)