티스토리 뷰

android

프리퍼런스 사용하기

노명규 2018. 11. 19. 13:21
package com.example.nmg.pref;

import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceUtil {

public static final String PREFERENCE_NAME = "wantName";
private static PreferenceUtil preferencemodule = null;
private static Context mContext;
private static SharedPreferences prefs;
private static SharedPreferences.Editor editor;

public static PreferenceUtil getInstance(Context context) {
mContext = context;

if (preferencemodule == null) {
preferencemodule = new PreferenceUtil();
}
if(prefs==null){
prefs = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
editor = prefs.edit();
}
return preferencemodule;
}


private int save(String key, int value) {
    editor.putInt(key, value);
editor.commit();
return value;
}

private String save(String key, String value) {
editor.putString(key, value);
editor.commit();
return value;
}

private long save(String key, long value) {
editor.putLong(key, value);
editor.commit();
return value;
}

private boolean save(String key, boolean value) {
editor.putBoolean(key, value);
editor.commit();
return value;
}

public String getId() { return prefs.getString("wantKey","default value"); }
public String setId(String 변수명) { return save("wantKey", 변수명); }

}


이렇게 하고


갖다 쓸땐



PreferenceUtil.getInstance(mContext).setId(editText.getText().toString());
String a = PreferenceUtil.getInstance(mContext).getId();





하면 깔끔하게 사용 가능