한 번의 활동을 만들기 위한 공유 환경설정
양식 데이터를 데이터베이스(SQLite)에 입력하고 저장한 후 A, B, C 세 가지 활동이 있습니다.저는 A에서 B로, 그리고 B에서 C로 의도를 사용하고 있습니다.제가 원하는 것은 앱을 열 때마다 더 이상 A와 B가 아닌 C를 홈 화면으로 원하는 것입니다.
선호도를 공유하는 것이 이에 효과가 있을 것으로 생각하지만, 시작점을 알려줄 좋은 예를 찾을 수 없습니다.
기본 설정에서 값 설정:
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
기본 설정에서 데이터 검색:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
추가 정보:
초기화 방법?
// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
데이터를 공유 기본 설정으로 저장하는 방법
editor.putString("key_name", "string value"); // Storing string
OR
editor.putInt("key_name", "int value"); //Storing integer
그리고 지원하는 것을 잊지 마세요.
editor.apply();
공유 기본 설정에서 데이터를 검색하는 방법은 무엇을 선택합니까?
pref.getString("key_name", null); // getting String
pref.getInt("key_name", 0); // getting Integer
이것이 U에게 도움이 되기를 바랍니다 :)
사용자 정의 Shared Preference 클래스를 만들 수 있습니다.
public class YourPreference {
private static YourPreference yourPreference;
private SharedPreferences sharedPreferences;
public static YourPreference getInstance(Context context) {
if (yourPreference == null) {
yourPreference = new YourPreference(context);
}
return yourPreference;
}
private YourPreference(Context context) {
sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
}
public void saveData(String key,String value) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
prefsEditor .putString(key, value);
prefsEditor.commit();
}
public String getData(String key) {
if (sharedPreferences!= null) {
return sharedPreferences.getString(key, "");
}
return "";
}
}
다음과 같은 기본 설정 인스턴스를 얻을 수 있습니다.
YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.saveData(YOUR_KEY,YOUR_VALUE);
String value = yourPreference.getData(YOUR_KEY);
저는 위의 모든 예시들이 너무 혼란스러워서 저만의 것을 썼습니다.코드 조각은 당신이 무엇을 하고 있는지 안다면 괜찮지만, 저처럼 모르는 사람들은 어떻습니까?
대신 컷앤페이스트 솔루션을 원하십니까?자, 여기 있습니다!
새 java 파일을 만들고 Keystore라고 합니다.그런 다음 다음 코드에 붙여넣습니다.
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class Keystore { //Did you remember to vote up my example?
private static Keystore store;
private SharedPreferences SP;
private static String filename="Keys";
private Keystore(Context context) {
SP = context.getApplicationContext().getSharedPreferences(filename,0);
}
public static Keystore getInstance(Context context) {
if (store == null) {
Log.v("Keystore","NEW STORE");
store = new Keystore(context);
}
return store;
}
public void put(String key, String value) {//Log.v("Keystore","PUT "+key+" "+value);
Editor editor = SP.edit();
editor.putString(key, value);
editor.commit(); // Stop everything and do an immediate save!
// editor.apply();//Keep going and save when you are not busy - Available only in APIs 9 and above. This is the preferred way of saving.
}
public String get(String key) {//Log.v("Keystore","GET from "+key);
return SP.getString(key, null);
}
public int getInt(String key) {//Log.v("Keystore","GET INT from "+key);
return SP.getInt(key, 0);
}
public void putInt(String key, int num) {//Log.v("Keystore","PUT INT "+key+" "+String.valueOf(num));
Editor editor = SP.edit();
editor.putInt(key, num);
editor.commit();
}
public void clear(){ // Delete all shared preferences
Editor editor = SP.edit();
editor.clear();
editor.commit();
}
public void remove(){ // Delete only the shared preference that you want
Editor editor = SP.edit();
editor.remove(filename);
editor.commit();
}
}
이제 그 파일을 저장하고 잊어버리세요.당신은 그것을 끝냈습니다.이제 다시 활동으로 돌아가서 다음과 같이 사용합니다.
public class YourClass extends Activity{
private Keystore store;//Holds our key pairs
public YourSub(Context context){
store = Keystore.getInstance(context);//Creates or Gets our key pairs. You MUST have access to current context!
int= store.getInt("key name to get int value");
string = store.get("key name to get string value");
store.putInt("key name to store int value",int_var);
store.put("key name to store string value",string_var);
}
}
Shared Preferences 개인 원시 데이터를 키-값 쌍으로 저장하는 XML 파일입니다.데이터 유형에는 부울, 플로트, int, long 및 문자열이 포함됩니다.
애플리케이션 전체에서 액세스할 수 있는 일부 데이터를 저장하려는 경우 글로벌 변수에 저장하는 것이 한 가지 방법입니다.하지만 애플리케이션이 닫히면 사라질 것입니다.권장되는 또 다른 방법은 저장하는 것입니다.SharedPreferenceShared Preferences 파일에 저장된 데이터는 응용프로그램 전체에서 액세스할 수 있으며 응용프로그램이 닫히거나 재부팅된 후에도 계속 유지됩니다.
Shared Preferences는 데이터를 키-값 쌍으로 저장하고 동일한 방식으로 액세스할 수 있습니다.
두 가지 방법을 사용하여 개체를 만들 수 있습니다.
.getSharedPreferences() : 이 메서드를 사용하여 MultipleSharedPreferences를 만들 수 있습니다.그리고 그것의 첫 번째 매개 변수는 다음과 같습니다.SharedPreferences.
.getPreferences() : 이 방법을 사용하여 Single을 만들 수 있습니다.SharedPreferences.
데이터 저장
변수 선언 추가/기본 설정 파일 생성
public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";
파일 이름으로 핸들 검색(getSharedPreferences 사용)
SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);
편집기 열기 및 키-값 쌍 추가
SharedPreferences.Editor myeditor = settingsfile.edit();
myeditor.putBoolean("IITAMIYO", true);
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply();
다음을 사용하여 적용/저장하는 것을 잊지 마십시오.myeditor.apply()상술한 바와 같이
데이터 검색 중
SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false);
//returns value for the given key.
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5)
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types
public class Preferences {
public static final String PREF_NAME = "your preferences name";
@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;
public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";
public static void writeBoolean(Context context, String key, boolean value) {
getEditor(context).putBoolean(key, value).commit();
}
public static boolean readBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);
}
public static void writeInteger(Context context, String key, int value) {
getEditor(context).putInt(key, value).commit();
}
public static int readInteger(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);
}
public static void writeString(Context context, String key, String value) {
getEditor(context).putString(key, value).commit();
}
public static String readString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);
}
public static void writeFloat(Context context, String key, float value) {
getEditor(context).putFloat(key, value).commit();
}
public static float readFloat(Context context, String key, float defValue) {
return getPreferences(context).getFloat(key, defValue);
}
public static void writeLong(Context context, String key, long value) {
getEditor(context).putLong(key, value).commit();
}
public static long readLong(Context context, String key, long defValue) {
return getPreferences(context).getLong(key, defValue);
}
public static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, MODE);
}
public static Editor getEditor(Context context) {
return getPreferences(context).edit();
}
}
****기본 설정을 사용하여 값 쓰기:-****
Preferences.writeString(getApplicationContext(),
Preferences.NAME, "dev");
****환경설정을 사용하여 값 읽기:-****
Preferences.readString(getApplicationContext(), Preferences.NAME,
"");
을 만드는 가장 SharedPreference글로벌 사용을 위해 아래와 같은 클래스를 만들어야 합니다.
public class PreferenceHelperDemo {
private final SharedPreferences mPrefs;
public PreferenceHelperDemo(Context context) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
private String PREF_Key= "Key";
public String getKey() {
String str = mPrefs.getString(PREF_Key, "");
return str;
}
public void setKey(String pREF_Key) {
Editor mEditor = mPrefs.edit();
mEditor.putString(PREF_Key, pREF_Key);
mEditor.apply();
}
}
SharedPreferences mPref;
SharedPreferences.Editor editor;
public SharedPrefrences(Context mContext) {
mPref = mContext.getSharedPreferences(Constant.SharedPreferences, Context.MODE_PRIVATE);
editor=mPref.edit();
}
public void setLocation(String latitude, String longitude) {
SharedPreferences.Editor editor = mPref.edit();
editor.putString("latitude", latitude);
editor.putString("longitude", longitude);
editor.apply();
}
public String getLatitude() {
return mPref.getString("latitude", "");
}
public String getLongitude() {
return mPref.getString("longitude", "");
}
public void setGCM(String gcm_id, String device_id) {
editor.putString("gcm_id", gcm_id);
editor.putString("device_id", device_id);
editor.apply();
}
public String getGCMId() {
return mPref.getString("gcm_id", "");
}
public String getDeviceId() {
return mPref.getString("device_id", "");
}
public void setUserData(User user){
Gson gson = new Gson();
String json = gson.toJson(user);
editor.putString("user", json);
editor.apply();
}
public User getUserData(){
Gson gson = new Gson();
String json = mPref.getString("user", "");
User user = gson.fromJson(json, User.class);
return user;
}
public void setSocialMediaStatus(SocialMedialStatus status){
Gson gson = new Gson();
String json = gson.toJson(status);
editor.putString("status", json);
editor.apply();
}
public SocialMedialStatus getSocialMediaStatus(){
Gson gson = new Gson();
String json = mPref.getString("status", "");
SocialMedialStatus status = gson.fromJson(json, SocialMedialStatus.class);
return status;
}
공유 기본 설정에 쓰기
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
공유 기본 설정에서 읽기
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
이 목적을 위해 작성된 제 과거 샘플 프로젝트도 보실 수 있습니다.나는 사용자의 요청에 따라 또는 앱이 시작될 때 로컬로 이름을 저장하고 검색합니다.
하지만, 지금은, 사용하는 것이 더 나을 것입니다.commit)로 표시됨)apply) 데이터를 유지합니다.자세한 내용은 여기.
Initialise here..
SharedPreferences msharedpref = getSharedPreferences("msh",
MODE_PRIVATE);
Editor editor = msharedpref.edit();
store data...
editor.putString("id",uida); //uida is your string to be stored
editor.commit();
finish();
fetch...
SharedPreferences prefs = this.getSharedPreferences("msh", Context.MODE_PRIVATE);
uida = prefs.getString("id", "");
// Create object of SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("name", required_Text);
//commits your edits
editor.commit();
// Its used to retrieve data
SharedPreferences sharedPref = getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
if (name.equalsIgnoreCase("required_Text")) {
Log.v("Matched","Required Text Matched");
} else {
Log.v("Not Matched","Required Text Not Matched");
}
공유 기본 설정은 배우기 쉬우므로 공유 기본 설정에 대한 이 간단한 튜토리얼을 살펴 보십시오.
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class UserSettingActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
언급URL : https://stackoverflow.com/questions/23024831/shared-preferences-for-creating-one-time-activity
'codememo' 카테고리의 다른 글
| CodeIgniter에서 pconnect 옵션의 장점/단점 (0) | 2023.08.21 |
|---|---|
| Android: 텍스트 편집에 초점을 맞출 때 자동으로 소프트 키보드 표시 (0) | 2023.08.21 |
| __init_.py에서 참조 'xxx'을(를) 찾을 수 없습니다. (0) | 2023.08.21 |
| Angular2가 비동기 함수 호출을 활성화()할 수 있습니다. (0) | 2023.08.21 |
| 전체 응용 프로그램을 세로 모드로만 설정하는 방법은 무엇입니까? (0) | 2023.08.21 |