android中保存数据的方式有
1,云存储(网络保存),
2,本地SharedPreferences保存少量数据,
3,本地文件流保存,
4,本地数据库保存。
下面讲的第2,3,4点;
2.SharedPreferences为程序持久化保存少量值:
<span style="font-size:18px;">获取SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);</span>
<span style="font-size:18px;">或者SharedPreferences sharedPref = getSharedPreferences(name, mode) 如果该文件不存在会自动创建</span>
<span style="font-size:18px;">
</span>
<span style="font-size:18px;">写入, SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();</span>
<span style="font-size:18px;">读取, SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE); </span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>int defaultValue =getResources().getInteger(R.string.saved_high_score_default); </span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>long highScore = sharedPref.getInt(getString(R.string.saved_high_score),defaultValue);</span>
存储路径又分为内部和外部存储。早期的手机设备区分的很明显。现在的手机可能会将一个存储空间直接划分成 这两个部分。内部存储,通常可用的,不用担心它悬挂,是app安装的路径(默认的,当然可以指定 app的安装路径android:installLocation),当app卸载后,app相关的文件会随之删除。当你想要用户和其他app无法访问该app的文件的时候可以考虑设置路径为这个。
内部路径,getFilesDir(),getCacheDir()
外部存储,通常是不可用的,因为用户会手动移除或者悬挂,所有在访问之前要判断外部存储的状态。
<span style="font-size:18px;">public boolean isExternalStorageWritable() { </span>
<span style="font-size:18px;">String state =Environment.getExternalStorageState(); </span>
<span style="font-size:18px;">if(Environment.MEDIA_MOUNTED.equals(state)) { </span>
<span style="font-size:18px;"><span style="white-space:pre"> </span>return true; </span>
<span style="font-size:18px;">} </span>
<span style="font-size:18px;">return false;</span>
<span style="font-size:18px;">}</span>
存储在这里的文件是可以被任何人和任何app访问的,而且当app卸载后,该文件不会自动删除,容易 造成垃圾文件。
使用外部存储空间,需要添加权限,<manifest ...> <uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ...
</manifest>
4.SQLiteOpenHelper数据库存储;步骤如下,
<span style="font-size:18px;">a.自定义类继承SQLiteOpenHelper
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}</span>
<span style="font-size:18px;">private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
... // Any other options for the CREATE command
" )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
public final class FeedReaderContract {
// To prevent someone from accidentally instantiating the contract class,
// give it an empty constructor.
public FeedReaderContract() {}
Inner class that defines the table contents
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
...
}
}</span>
下面的增删查改都需要在子线程中进行;
<span style="font-size:18px;">b.写入数据,
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
FeedEntry.TABLE_NAME,
FeedEntry.COLUMN_NAME_NULLABLE,
values);
c.读出数据,
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_UPDATED,
...
};
// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_UPDATED + " DESC";
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
d.删除数据,
// Define 'where' part of query.
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
// Specify arguments in placeholder order.
String[] selectionArgs = { String.valueOf(rowId) };
// Issue SQL statement.
db.delete(table_name, selection, selectionArgs);
e.更新数据,
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// New value for one column
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
// Which row to update, based on the ID
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);</span>