Android 数据保存
Android数据保存方法
- Context context = getActivity();
- SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key),Context.MODE_PRIVATE);
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
向共享参数文件中写入数据
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
- SharedPreferences.Editor eidtor = sharedPref.edit();
- editor.putInt(getString(R.string.save_high_score),newHighScore);
- editor.commit();
从共享参数文件中读取数据
- SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
- int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
- long highScore = sharedPref.getInt(getString(R.sting.saved_high_score),defaultValue);
将数据保存于文件中
获取外部存储设备的访问许可
- <mainifets ...>
- <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE”/>
- </manifest>
- <manifest ...>
- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
- ...
- </manifest>
将文件保存到内部存储器
- File file = new File(context.getFilesDir(),filename);
- String filename = "myfile";
- String string = "Hello world!";
- FileOutPutStream outputStream;
- try{
- outputStream = openFileOutput(filename,Context.MODE_PRIVATE);
- outputStream.write(string.getBytes());
- outputStream.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- public File getTempFile(Context context,String url){
- File file;
- try{
- String filename = Uril.parse(url).getLastPathSegment();
- file = File.createTempFile(filename,null,context.getCacheDir());
- }catch(IOException e){
- //
- }
- return file;
- }
将文件保存到外部存储器
- //该方法判断外部存储器是否挂载上(是否可读写)。
- public boolean isExternalStorageWritable(){
- String state = Environment.getExternalStorageState();
- if(Environment.MEDIA_MOUNTED.equals(state)){
- returen true;
- }
- return false;
- }
- //检查外部存储器是否至少为可读的
- public boolean isExternalStorageReadable(){
- String state = Environment.getExternalStorageState();
- if(Environment.MEDIA_MOUNTED.equals(state) ||
- Environment.MEIDA_MOUNTED_READ_ONLY.equals(state)){
- returen true;
- }
- return false;
- }
- //该方法获取用户的公共图片文件夹文件
- public File getAlbumStorageDir(String albumName){
- File file = new File(Environment.getExternalStoragePublicDirectory(Evironment.DIRECTORY_PICTURES),albumName);
- if(!file.mkdirs()){
- Log.e(LOG_TAG,"Directory not created");
- }
- return file;
- }
- public File getAlbumStorageDir(Context context,String albumName){
- //Get the directory for the app‘s private pictures directory.
- File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES),albumName);
- if(!file.mkdirs()){
- Log.e(LOG_TAG,"Directory not created");
- }
- return file;
- }
查询剩余空间
文件的删除
- myContext.deleteFile(fileName);
将数据保存到SQL数据库中
定义数据库表结构
- public final class FeedReaderContract {
- public FeedReaderContract() {}
- //内部类定义表结构
- 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";
- ...
- }
- }
使用SQL Helper 来创建一个数据库:
- 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;
android将数据保存到程序的私有磁盘空间中,通常这里保存的数据不能被其他应用程序访问
要使用SQLiteOpenHelper类,需要实现其子类,该子类覆盖了onCreate(),onUpgrade(),onOpen()方法,你也可以。
- 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);
- }
- }
使用我们自定已的SQLiteOpenHelper类
- FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
- SQLiteDatabase db = mDbHelper.getWritableDatabase();
- 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);
- long newRowId;
- newRowId = db.insert(FeedEntry.TABLE_NAME,
- FeedEntry.COLUMN_NAME_NULLABLE,
- values);
- 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
- );
- <h2><a name="t14"></a>读取Cursor中的数据</h2>cursor.moveToFirst();
- long itemId = cursor.getLong(
- cursor.getColumnIndexOrThrow(FeedEntry._ID)
- );
删除数据库中的数据
- String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
- String[] selectionArgs = { String.valueOf(rowId) };
- db.delete(table_name, selection, selectionArgs);
更新数据库数据
- SQLiteDatabase db = mDbHelper.getReadableDatabase();
- ContentValues values = new ContentValues();
- values.put(FeedEntry.COLUMN_NAME_TITLE, title);
- String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
- String[] selectionArgs = { String.valueOf(rowId) };
- int count = db.update(
- FeedReaderDbHelper.FeedEntry.TABLE_NAME,
- values,
- selection,
- selectionArgs);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。