Android基礎(二)資料儲存1.SharedPreferences儲存
阿新 • • 發佈:2018-12-13
SharedPreferences經常用來儲存一些預設歡迎語,使用者登入名和密碼等簡單資訊,一般用於儲存量小的資訊 exampleHelper.java
import android.content.Context; import android.content.SharedPreferences; /** * Created by 6lang on 2018/10/6. */ public class exampleHelper { SharedPreferences sp; SharedPreferences.Editor editor; Context context; public exampleHelper(Context c,String name) { context=c; sp=context.getSharedPreferences(name,0); editor=sp.edit(); } public void putValue(String key,String value) { editor=sp.edit(); editor.putString(key,value); editor.commit(); } public String getValue(String key) { return sp.getString(key,null); } }
1getSharedPreferences(檔名稱,操作模式) .得到SharedPreferences物件,0表示預設模式 2.editor=sp.edit(); 獲取一個Edit物件,所有對資料的操作都需要經過Edit 3.editor.commit(); 提交是必須的 MainActivity.java
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public final static String COLUMN_NAME="name"; public final static String COLUMN_MOBILE="mobile"; exampleHelper sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sp=new exampleHelper(this,"contact"); //設定儲存的資訊 sp.putValue(COLUMN_NAME,"Mr Wang"); sp.putValue(COLUMN_MOBILE,"13223346556"); String name=sp.getValue(COLUMN_NAME); String mobile=sp.getValue(COLUMN_MOBILE); TextView tv=new TextView(this); tv.setText("NAME:"+name+"\n"+"MOBILE:"+mobile); setContentView(tv); } }