2011-09-20 4 views
7

SharedPreference를 복사하거나 복제 할 수있는 방법이 있습니까? 아니면 하나에서 각 변수를 가져와 다른 변수에 넣어야합니까? 이처럼Android : Copy/Duplicate SharedPreferences

+0

각 변수를 하나씩 가져 와서 다른 변수를 넣으면됩니다. 그러나 SharedPrefs는 xml 파일로 저장됩니다. 전체 파일을 복사하여 새 이름으로 붙여 넣을 수 있다고 생각합니다. 이 방법을 사용하면 응용 프로그램 SharedPreferences 폴더에 설정된 입력 및 출력 스트림을 가져올 수 있지만 루팅 된 장치가 필요할 수 있습니다. – FoamyGuy

+0

공유 설정을 왜 복사 하시겠습니까? 귀하의 성취하고자하는 바를 조금 더 자세하게 설명하십시오. 그러면 우리가 적절한 대답을 제공하는 데 도움이 될 것입니다. – Kenny

+0

내 앱은 변수를 sharedpreference에 저장합니다. 50 개의 변수가 끊임없이 변합니다. 즉, 앱에서 하드 코드 될 수 없습니다. 이러한 변수를 별도로 설정하여 앱 사용자가 새 세션을 시작한 다음 두 세션을 번갈아 가며 전환 할 수 있기를 바랍니다. 나는 그것을 빨아 들일 수 있고 모든 변수를 다른 sharedpreference에 쓸 수 있다고 가정한다. 그러나 이것을 할 수 있다면 훨씬 쉬울 것이다 : savedSharedPreference = sharedPreference. LoL – cerealspiller

답변

12

시도 뭔가 :이 도움이

//sp1 is the shared pref to copy to 
SharedPreferences.Editor ed = sp1.edit(); 
SharedPreferences sp = Sp2; //The shared preferences to copy from 
ed.clear(); // This clears the one we are copying to, but you don't necessarily need to do that. 
//Cycle through all the entries in the sp 
for(Entry<String,?> entry : sp.getAll().entrySet()){ 
Object v = entry.getValue(); 
String key = entry.getKey(); 
//Now we just figure out what type it is, so we can copy it. 
// Note that i am using Boolean and Integer instead of boolean and int. 
// That's because the Entry class can only hold objects and int and boolean are primatives. 
if(v instanceof Boolean) 
// Also note that i have to cast the object to a Boolean 
// and then use .booleanValue to get the boolean 
    ed.putBoolean(key, ((Boolean)v).booleanValue()); 
else if(v instanceof Float) 
    ed.putFloat(key, ((Float)v).floatValue()); 
else if(v instanceof Integer) 
    ed.putInt(key, ((Integer)v).intValue()); 
else if(v instanceof Long) 
    ed.putLong(key, ((Long)v).longValue()); 
else if(v instanceof String) 
    ed.putString(key, ((String)v));   
} 
ed.commit(); //save it. 

희망.

+0

고마워! 나는 이것을 최대한 빨리 시도 할 것인가 – cerealspiller

+3

도움이된다면 답을 받아들이거나 upvote하는 것을 잊지 마라;) – zarthross

+1

이것은 답으로 받아 들여 져야한다. 또한 당신은 추가 할 수 있습니다 : \t \t은/* 사용자 설정이 설정 활동에 지속적으로 만들어 */\t \t (SystemUtils.getSDKVersion()> Build.VERSION_CODES.FROYO)의 경우 { \t \t \t editor.apply(); \t \t} else { \t \t \t editor.commit(); \t \t} –

7

문자열 세트도 지원하는 버전입니다.

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences) { 
    copySharedPreferences(fromPreferences, toPreferences, true); 
} 

public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences toPreferences, boolean clear) { 

    SharedPreferences.Editor editor = toPreferences.edit(); 
    if (clear) { 
     editor.clear(); 
    } 
    copySharedPreferences(fromPreferences, editor); 
    editor.commit(); 
} 

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
@SuppressWarnings({"unchecked", "ConstantConditions"}) 
public static void copySharedPreferences(SharedPreferences fromPreferences, SharedPreferences.Editor toEditor) { 

    for (Map.Entry<String, ?> entry : fromPreferences.getAll().entrySet()) { 
     Object value = entry.getValue(); 
     String key = entry.getKey(); 
     if (value instanceof String) { 
      toEditor.putString(key, ((String) value)); 
     } else if (value instanceof Set) { 
      toEditor.putStringSet(key, (Set<String>) value); // EditorImpl.putStringSet already creates a copy of the set 
     } else if (value instanceof Integer) { 
      toEditor.putInt(key, (Integer) value); 
     } else if (value instanceof Long) { 
      toEditor.putLong(key, (Long) value); 
     } else if (value instanceof Float) { 
      toEditor.putFloat(key, (Float) value); 
     } else if (value instanceof Boolean) { 
      toEditor.putBoolean(key, (Boolean) value); 
     } 
    } 
} 
관련 문제