1

ユーザーがテキストを挿入して将来の読み取りに保存できる日記として機能するはずのアプリケーションがあります。各エントリは、tableLayout に重ねて格納されます。

私はこのテキストを配列に入れており、tableLayout を永続的にしたいのです。つまり、destroy が呼び出された場合でも、Shared Preferences を使用する必要があります。

たとえば、ユーザーが再起動後にアプリを開いた場合、すべての行を復元するにはどうすればよいですか?

ありがとうございました

4

1 に答える 1

2

API レベル 11 以上を使用している場合は、 関数getStringSet()putStringSet()関数を使用できます。次に例を示します。

SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

String yourArray = new String [] {"Hello", "World", "How", "Are", "You"};
editor.putStringSet(new HashSet(Arrays.asList(yourArray)), "test");

そしてそれを取り戻します:

Set<String> data = prefs.getStringSet("test", null);

低レベルの API を使用している場合:

書いてください:

//context - a context to access sharedpreferences
//data[] - the array you want to write
//prefix - a prefix String, helping to get the String array back.

public static void writeList(Context context, String [] data, String prefix)
{
    SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    int size = data.length;

    // write the current list
    for(int i=0; i<size; i++)
        editor.putString(prefix+"_"+i, data[i]);

    editor.putInt(prefix+"_size", size);
    editor.commit();
}

それを取得します。

public static String[] readList (Context context, String prefix)
{
    SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);

    int size = prefs.getInt(prefix+"_size", 0);

    String [] data = new String[size];
    for(int i=0; i<size; i++)
        data[i] = prefs.getString(prefix+"_"+i, null);

    return data;
}

リスト全体を削除します。

public static int removeList (Context context, String prefix)
{
    SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    int size = prefs.getInt(prefix+"_size", 0);

    for(int i=0; i<size; i++)
        editor.remove(prefix+"_"+i);

    editor.commit();
    return size;
}

これを使って:

(これはあなたの活動にあるはずです)

//write it:
String yourArray = new String [] {"Hello", "World", "How", "Are", "You"};
writeList(this, yourArray, "test");

//get it back:
String yourArray = readList(this, "test");

//delete it:
removeList(this, "test");
于 2012-09-01T16:25:00.663 に答える