android中的保存数据方法
16lz
2021-01-25
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 modeSQLiteDatabase db = mDbHelper.getWritableDatabase();// Create a new map of values, where column names are the keysContentValues 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 rowlong 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 CursorString 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 columnContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_TITLE, title);// Which row to update, based on the IDString selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";String[] selectionArgs = { String.valueOf(rowId) };int count = db.update( FeedReaderDbHelper.FeedEntry.TABLE_NAME, values, selection, selectionArgs);</span>
更多相关文章
- 一款常用的 Squid 日志分析工具
- GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
- “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
- Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
- 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
- android SDK启动的错误
- Android(安卓)studio的安装、环境配置和使用方法