全栈工程师开发手册 (作者:栾鹏)
安卓数据存储和读取全解。
SharedPreferences读写共享数据
//写入共享数据
public void set_data(Context context,String key,String value) {
SharedPreferences myPreferences = context.getSharedPreferences("set", Activity.MODE_PRIVATE); //获取共享数据,各组件间可共享
SharedPreferences.Editor editor = myPreferences.edit(); //获取编辑器
editor.putString(key, value); //设置数据
// editor.putBoolean(key, value);
// editor.putFloat(key, value);
// editor.putLong(key, value);
// editor.putStringSet(key, values);
editor.apply(); //保存
}
//读取共享数据
public Object get_data(Context context,String key) {
SharedPreferences myPreferences = context.getSharedPreferences("set", Activity.MODE_PRIVATE); //获取共享数据,各组件间可共享
String back="";
if (myPreferences.contains(key)) { //判断是否存在指定属性
back= myPreferences.getString(key, "默认值"); //读取数据,可设置默认值。有读取各种类型数据的函数
}
//Map<String, ?> alldata = myPreferences.getAll(); //获取所有数据
return back;
}
SQLiteDatabase数据库中数据的增删查改
//SQLite创建新的数据库,名称为myDatabase,模式为MODE_PRIVATE,鼠标工厂
public static SQLiteDatabase creatsql(Context context) {
SQLiteDatabase myDataBase=context.openOrCreateDatabase("myDataBase.db",Context.MODE_PRIVATE, new CursorFactory(){
//创建新的数据库,名称myDatabase,模式MODE_PRIVATE,鼠标工厂
//工厂类,一个可选工厂类,当查询时调用来实例化一个光标
@Override
public Cursor newCursor(SQLiteDatabase db,SQLiteCursorDriver masterQuery, String editTable,SQLiteQuery query) {
// TODO 自动生成的方法存根
return null;
}
});
return myDataBase;
//context.deleteDatabase("myDataBase.db"); //删除数据库
}
//SQLite非查询sql语言
public static void execsql(SQLiteDatabase myDataBase,String command){
myDataBase.execSQL(command);
}
//SQLite查询sql语句
public static List<HashMap<String, Object>> querysql(SQLiteDatabase myDataBase,String command){
Cursor cursor = myDataBase.rawQuery(command, null);
List<HashMap<String, Object>> alldata = new ArrayList<HashMap<String,Object>>();
if(cursor!=null){ //游标不为空
//返回给定名称的列的基于0开始的index,如果该属性列不存在则返回-1
if(cursor.moveToFirst()){
//cursor.moveToFirst()让游标指向第一行,如果游标指向第一行,则返回true
String[] columnnames = cursor.getColumnNames(); //获取结果集中的所有列名
do {
HashMap<String, Object> onedata =new HashMap<String, Object>();
for (int i=0;i<columnnames.length;i++) {
onedata.put(columnnames[i], cursor.getString(i)); 获得当前行该列的值,通过列索引读取
//Cursor提供了不同的方法来回索不同的数据类型 ,例如getInt(int index)/getString(int index)等等
}
alldata.add(onedata);
} while (cursor.moveToNext());
//游标移动到下一行,如果游标已经通过了结果集中的最后,即没有行可以移动时,则返回false
//移动函数:moveToprevious()、moveTofirst()、moveToPosition(int index)方法
//获取函数:getPosition返回游标位置,getCount返回行数,getColumnName(int index)获取指定列名,getColumnNames返回所有列名字符串,getColumnIndex(string);获取指定名称的列
}
}
myDataBase.close(); //关闭数据库
return alldata;
}