Android笔记之数据存储

四大存储方式:

  • 文件系统:保存在本地文件中,使用JavaIO流技术实现对数据的读写
  • 数据库:SQLite数据库:性能和安全都很好
  • 云服务:网络通信技术访问
  • Shared Preferences:存放少量的“键-值”对形式的数据(控件状态,用户偏好)

实例:健康助手设计

  • 用户实现:增、删、改、查---->数据的操作
  • 数据库设计:设计表、字段。
  • 本地文件格式设计:自己设定格式,并按照此格式读写文件

Android平台,应用程序目录(/data/data/<应用包名>)采用沙箱目录设计,这样更安全。

  • 在<sdk安装目录>\sdk\platform-tools目录,运行adb shell 进入模拟器的shell
  • 访问应用程序的files目录:
  • 打开IO流对象:
//打开文件输入流
FileInputSream openFileInput(String name) throws FileNotFoundException

//打开文件输出流
FileOutputStream openFileOutput(String name, Int mode) throws FileNotFoundException

注:name是文件名(不需要指定文件路径)

Mode:是打开文件的方式:(多个模式之间用 | 连接)

MODE_APPEND //文件末写入数据的方式打开文件
MODE_PRIVATE //只允许当前应用自己读写创建文件
MODE_WORLD_READABLE //其他应用程序允许可读创建文件
MODE_WORLD_WRITEABLE //其他应用程序允许可写创建文件

实例:访问CSV文件

  1. 将csv文件写入file文件夹
  2. 将文件读取出来,打印日志
FileOutputStream out = null;

try {
    StringBuffer rows = new StringBuffer();
    rows.append("1289645040579,1500大卡,3000大卡,90kg,5公里");
    rows.append("\n");
    out = this.openFileOutput(SysConst.DATABASE_NAME, MODE_PRIVATE);
    out.write(rows.toString().getBytes("utf-8"));
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (out != null) {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }
}
private List<Map<String, String>> findAll() {
    FileInputStream in = null;
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    try {
        in = this.openFileInput(SysConst.DATABASE_NAME);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String line = br.readLine();
        while (line != null) {
            String[] fields = line.split(",");
            Map<String, String> rows = new HashMap<String, String>();
            rows.put(SysConst.TABLE_FIELD_DATE, fields[0]);//..........
            list.add(rows);
            line = br.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return list; 
}

SQlite数据库:(字段不用指定类型)

  • 可移植性
  • 易使用
  • 高效
  • 可靠

Create Tablestudent(_id,name,class)

  • INTEGER:有符号的整数类型
  • REAL:浮点类型
  • TEXT:字符串类型
  • BLOB:二进制对象类型

文件目录在databases

SQLite命令行管理:

  • .help: 查看帮助
  • .quit: 退出SQLite命令行
  • .tables: 显示库中所有的表
  • .schema: 显示表的结构

SQLiteOpenHelper帮助类:

//必须实现两个方法
void onCreate(SQLiteDatabase db)
void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)

DBHelper构造方法:上下文对象,数据库文件名字,Cursor子类,数据库版本号

SQLiteOpenHelper(Context context,String name,CursorFactory factory,int version)

public void onCreate(SQLiteDatabase db) {
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("CREATE TABLE ");
            sql.append(SysConst.TABLE_NAME);
            sql.append(" (");
            sql.append(SysConst.TABLE_FIELD_DATE);
            sql.append(" Text PRIMARY KEY,");
            sql.append(SysConst.TABLE_FIELD_INPUT);
            sql.append(" Text,");
            sql.append(SysConst.TABLE_FIELD_OUTPUT);
            sql.append(" Text,");
            sql.append(SysConst.TABLE_FIELD_WEIGHT);
            sql.append(" Text ,");
            sql.append(SysConst.TABLE_FIELD_AMOUNTEXERCISE);
            sql.append(" Text");
            sql.append(");");
            Log.i(TAG, sql.toString());
            db.execSQL(sql.toString());

            //插入两条测试数据
            db.execSQL("insert into weight (_id,output,input) " +"values('2016-10-8 17:24:27','1300大卡','3300大卡')");

            db.execSQL("insert into weight (_id,output,input) " +"values('2016-10-9 15:26:45','2500大卡','4000大卡')");
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + SysConst.TABLE_NAME);
        onCreate(db);
    }

添加数据:

public void onClick(View v) {
    Date date = new Date();
    SimpleDateFormat df = new SimpleDateFormat(SysConst.DATE_FORMATE);
    SQLiteDatabase db = mDBHelper.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(SysConst.TABLE_FIELD_DATE, df.format(date));
    values.put(SysConst.TABLE_FIELD_INPUT, txtInput.getText().toString());
    values.put(SysConst.TABLE_FIELD_OUTPUT, txtOutput.getText().toString());
    values.put(SysConst.TABLE_FIELD_WEIGHT, txtWeight.getText().toString());
    values.put(SysConst.TABLE_FIELD_AMOUNTEXERCISE,txtAmountExercise.getText().toString());

    //不会抛出异常的方法
    //public long insert(String table,String nullColumnHack,ContentValues values)
    long rowId = db.insert(SysConst.TABLE_NAME, null, values);
    finish();

}

数据的删除:

SQLiteDatabase db = mDBHelper.getWritableDatabase();
String whereClause = SysConst.TABLE_FIELD_DATA + “= ?”;
Long rowId = db.delete(SysConst.TABLE_NAME,whereClause,new String[]{selectId});

//SQLiteDatabase提供的delete方法:表名,条件,数据
Public int delete (String table,String whereClause,String[] whereArgs)

数据的修改:

String whereClause = SysConst.TABLE_FIELD_DATE + " = ?";
long rowId = db.update(SysConst.TABLE_NAME, values, whereClause, new String[]{selectId});

数据的查询:

SQLiteDatabase db = mDBHelper.getReadableDatabase();
String[] colums = new String[]{SysConst.TABLE_FIELD_DATE,
SysConst.TABLE_FIELD_INPUT, SysConst.TABLE_FIELD_OUTPUT,
SysConst.TABLE_FIELD_WEIGHT,
SysConst.TABLE_FIELD_AMOUNTEXERCISE};
mCursor = db.query(SysConst.TABLE_NAME, colums, null, null, null, null,
SysConst.TABLE_FIELD_DATE + " asc");

while (mCursor.moveToNext()) {
    Log.d(TAG, Cursor.getString(mCursor.getColumnIndex(SysConst.TABLE_FIELD_INPUT)));
    Log.d(TAG, mCursor.getString(mCursor.getColumnIndex(SysConst.TABLE_FIELD_OUTPUT)));
}

startManagingCursor(mCursor);
mCursorAdapter = new SimpleCursorAdapter(this, R.layout.listitem, mCursor,
colums, new int[]{R.id.date, R.id.input, R.id.output,R.id.weight, R.id.amountExercise});
mListView.setAdapter(mCursorAdapter);

SharedPreferences偏好存储:

// 获得读取存数据所用的SharedPreferences对象
mSharedPreferences = getSharedPreferences(SysConst.PREFS_CONF, MODE_PRIVATE);
rdgDateFormat = (RadioGroup) findViewById(R.id.rdgDateFormat);
rdDateFormat1 = (RadioButton) findViewById(R.id.rdDateFormat1);
rdDateFormat2 = (RadioButton) findViewById(R.id.rdDateFormat2);

// 读取DATE_KEY键所对应的值
String dateConf = mSharedPreferences.getString(SysConst.DATE_KEY, "YYYY-MM-DD");
setDateFormat(dateConf);

rdgDateFormat.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // 获得修改数据所用的SharedPreferences对象
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        if (checkedId == rdDateFormat1.getId()) {
            editor.putString(SysConst.DATE_KEY, "YYYY-MM-DD");
            setDateFormat("YYYY-MM-DD");
        } else {
            editor.putString(SysConst.DATE_KEY, "YYYY/MM/DD");
            setDateFormat("YYYY/MM/DD");
        }
        // 确定修改
        editor.commit();
    }
});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值