android中的数据存储大致可以分为三种,第一种是通过文件流的方式;第二种是利用SharedPreferences,第三种是使用android提供的SQLite。总体看来,前两种适用于处理小型数据的读取和修改,第三种方法中,SQLite其实就是一个数据库,通过编写建表和查询语句等就可以处理较为大量的数据。
第一种方法
需要在AndroidManifest.xml文件中添加文件读写权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
具体的代码为:
private void readFromSD() {
FileInputStream input;
try {
// set the path to the file in the SD card
input = new FileInputStream("/sdcard/lyricInSD");
BufferedReader reader = new BufferedReader(new InputStreamReader(
input));
String string = "";
String line = null;
while ((line = reader.readLine()) != null) {
string = string + line + "\n";
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void saveToSD() {
String string = "the string save to SD card";
FileOutputStream output;
try {
// set the file path to the SD card
output = new FileOutputStream("/sdcard/lyricInSD");
output.write(string.getBytes());
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
第二种方法SharedPreferences
private void savesharedPreferences() {
SharedPreferences preferences = getSharedPreferences("dataText", Context.MODE_WORLD_READABLE);
Editor tempEditor = preferences.edit();
tempEditor.putString("name", "the name to save");
tempEditor.putString("age", "the age to save");
tempEditor.putString("height", "the height to save");
tempEditor.commit();
}
private void loadsharedPreferences() {
SharedPreferences preferences = getSharedPreferences("dataText", Context.MODE_PRIVATE);
String nameString = preferences.getString("name", "Default value");
String ageString = preferences.getString("age", "Default value");
String heightString = preferences.getString("height", "Default value");
}
第三种方法SQLite,先封装一个dataAadatper类。
public class dataAdatper {
public static final String KEY_NAME = "name";
public static final String KEY_INTRO = "intro";
public static final String KEY_ID = "id";
//建表语句,设置id为自动增加,还有注意一旦修改了建表语句,需要同时把手机中对应的数据表手动删除
private static final String DATABASE_CREATE = "create table member (id integer primary key autoincrement, "
+ "name text, intro text);";
private static final String DATABASE_NAME = "memberDB";
private static final String DATABASE_TABLE = "member";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static class DatabaseHelper extends SQLiteOpenHelper {
/* 构造函数 */
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/* 创建一个表 */
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
/* 升级数据库 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
/**
* 构造函数-取得context
* */
public dataAdatper(Context ctx) {
this.mCtx = ctx;
}
/**
* 打开数据库,返回数据库对象
* */
public dataAdatper open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
/**
* 关闭数据库
* */
public void close() {
mDbHelper.close();
}
/**
* 插入一条数据,并返回该数据对应的id
* */
public int createRecord(String name, String intro) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_INTRO, intro);
return mDb.insert(DATABASE_TABLE, null, cv);
}
/**
* 删除一条数据
* */
public boolean deleteRecord(int ID) {
return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + ID, null) > 0;
}
/**
* 通过Cursor查询所有数据
* */
public Cursor fetchAllRecords() {
Cursor cursor = mDb.query(DATABASE_TABLE, new String[] { KEY_ID,
KEY_NAME, KEY_INTRO }, null, null, null, null, null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
return cursor;
}
/**
* 通过ID查询指定的数据
* */
public Cursor fetchRecord(long ID) throws SQLException {
Cursor cursor = mDb.query(true, DATABASE_TABLE, new String[] { KEY_ID,
KEY_NAME, KEY_INTRO }, KEY_ID + "=" + ID, null, null, null,
null, null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
return cursor;
}
/**
* 更新一条数据
* */
public boolean updateRecord(long ID, String name, String intro) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_INTRO, intro);
return mDb.update(DATABASE_TABLE, cv, KEY_ID + "=" + ID, null) > 0;
}
}
在主程序中调用相关的操作函数以及获取数据并解析。
private void test() {
dataAdatper sqlData = new dataAdatper(this);
sqlData.open();
// 插入一条数据,s1和s2为字符串参数
sqlData.createRecord(s1, s2);
// 删除一条数据,id为数据对应的id
sqlData.deleteRecord(id);
// 更新数据库中的数据
sqlData.updateRecord(id, s1, s2);
// 获取所有数据并解析
Cursor cursor = sqlData.fetchAllRecords();
if (cursor.getCount() > 0) {
// name为数据表中的一个属性值,通过getColumnIndex获取属性值对应的下标
int index = cursor.getColumnIndex("name");
do {
// 获取name属性值存储的数据
cursor.getString(index);
} while (cursor.moveToNext()); // 移动cursor
}
}