Android-存儲數據的幾種方法

1.Android用Java開發,可以使用全局變量

public String picpath;
public String hasfind;
public String ProductID="0";

這種方法適用於程序運行期間,需要多個地方用到的臨時值有用

,比如上傳圖片的路徑,截圖的路徑等,因爲這些值都是其他activity產生的,後來可能在其他activity中使用,但是我不想在activity間傳來傳去,

剛脆扔到全局變量裏,這樣修改起來也方便.但是全局變量只在內存中保存,程序關閉後數據就不存在了.那麼我要保存持久的數據該怎麼保存呢,

你首先肯定想到了數據庫,對沒錯,數據庫是存儲數據最好的地方,但是作爲移動端,只是一個客戶端不可能把用戶的數據都保存在手機上吧,智能機

怎麼能離開網絡?數據庫固然可以,但是重複的讀寫數據庫真的沒有必要,客戶端只需要存取少量的數據,既然應用都離不開網絡,那用時再去服務器

上取就是了,但是還有一些必須保存在客戶手機上得東西,不得不存在客戶端,像用戶名\密碼\授權token~~~

2.SharedPreferences存儲用戶名 密碼等信息

SharedPreferences和iOS下plist一樣實際是個xml文件,裏面的數據以鍵值對來保存在客戶端的數據

SharedPreferences sp = context.getSharedPreferences("userinfo",0);
username = sp.getString("username", "");Editor editor = sp.edit();      
							
editor.putString("username", username);
						        	editor.putString("password", enpwd);
						        	editor.commit();

3.Properties

這個一般用來保存應用的配置文件信息,學Java的都認識這個文件吧,安卓裏一樣適用,這些配置文件一般保存在應用安裝目錄下,防止用戶刪除或者<惡意修改信息,我本人更喜歡用Properties,本質上它也是鍵值對保存數據


尼瑪csdn的默認編輯器還能再垃圾一點嗎!!!!!!

/**
	 * 得到配置文件
	 * @return
	 */
	public Properties getProp() {
		FileInputStream fis = null;
		Properties props = new Properties();
		try{
			
			
			//讀取app_path目錄下的config
			File dirConf = mContext.getDir(path, Context.MODE_PRIVATE);
			fis = new FileInputStream(dirConf.getPath() + File.separator + APP_CONFIG);
			
			props.load(fis);
<p class="p1"><span style="white-space:pre">			</span>String value = props.getProperty(key);</p>		}catch(Exception e){
		}finally{
			try {
				fis.close();
			} catch (Exception e) {}
		}
		return props;
	}

4.數據庫SQLite

Android和iOS都自帶了sqlite數據庫,這個數據庫雖小,但是膽小精悍,基本的SQL語句都支持,連接 訪問也簡單,適合保存大量的數據在客戶端.

SQLiteDatabase db = context.openOrCreateDatabase("my.db",
				MODE_PRIVATE, null);//創建或打開數據庫
db.execSQL(CREATE_TABLE_SQL);//執行創建表SQL
String sqlbrand = "select distinct b.id,b.name  from ProductBrands b inner join   Product c on b.id=c.brandsid and c.banchyn='0' and c.showinsellthrough='1'  ";//查詢所有品牌
		 String id = "";
		 String type ="";
		 String brand ="";

		 Cursor cursor2 = db.rawQuery(sqlbrand, null);//執行查詢語句
			while(cursor2.moveToNext()){
				id = cursor2.getString(0);
				brand = cursor2.getString(1);
				brandlist.add(new Product(id, brand));
			}
			cursor2.close();
			db.close();
			
		
5.網絡





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章