SharedPreferenceをコピーまたは複製する方法はありますか?あるいは、私は各変数を1つずつ取得し、別の変数に入れなければなりませんか?Android:Copy/Duplicate SharedPreferences
//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.
・ホープ、このことができます:
それぞれの変数を1つずつ取得し、別の変数に入れてみるとわかります。しかし、SharedPrefsはxmlファイルとして保存されています。あなたはそのファイル全体をコピーして、何らかの形で新しい名前で貼り付けることができるかもしれないと思います。このアプローチでは、アプリのSharedPreferencesフォルダに入力ストリームと出力ストリームを設定できるようにするために、ルートデバイスが必要になる場合があります。 – FoamyGuy
なぜ共有設定をコピーしますか?あなたの達成しようとしていることをもう少し詳しく説明し、それが適切な答えを提供するのに役立つでしょう。 – Kenny
私のアプリは変数をsharedpreferenceに格納しています。私は絶えず変化している約50の変数を持っています。言い換えれば、それらはアプリケーションでハードコーディングできません。これらの変数を脇に置いて、アプリユーザーが新しいセッションを開始してから2つのセッションを切り替えることができるようにしたいと考えています。私はそれを吸うことができ、別のsharedpreferenceにすべての変数を書き込むことができますが、私はちょうどこれを行うことができればもっと簡単だろう:savedSharedPreference = sharedPreference。 LoL – cerealspiller