這次我們寫成一個Class 讓之後再次使用更佳的方便
import android.content.Context;
import android.content.SharedPreferences;
public class MemoryClass {
        public static final String PREFERENCES_NAME = "Hello";
        public static final String NAME = "NAME";
        
        public static void setName(Context context,String name) {
                SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME,        
                                Context.MODE_PRIVATE);
                sp.edit().putString(NAME, name).commit();
        }
        public static String getName(Context context) {
                SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME,        
                                Context.MODE_PRIVATE);
                return sp.getString(NAME, "");
        }
        
}
當我們要調用時,只需要做簡單的呼叫
// 儲存文字內容
MemoryClass.setName(MainActivity.this, "John");
// 讀取指定參數
String name = MemoryClass.getName(MainActivity.this);
歡迎轉載,請註明出處。
 
沒有留言:
張貼留言