1. 程式人生 > >android中的儲存資料方法

android中的儲存資料方法

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>
3.本地檔案儲存
儲存路徑又分為內部和外部儲存。早期的手機裝置區分的很明顯。現在的手機可能會將一個儲存空間直接劃分成 這兩個部分。內部儲存,通常可用的,不用擔心它懸掛,是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>