2

DatabaseHandler というクラスがあり、基本的に連絡先のデータベースを処理します。Android エミュレーターを開くと、連絡先を追加および削除できます。次に、エミュレーターを閉じて再度開くと、連絡先が保持されるため、データベースに連絡先が保存されます。

私の問題はこれです。次のように、連絡先クラスに変数があります。

public static int totalContacts = 0;

この変数は、データベース内の連絡先の総数を追跡するため、連絡先を追加すると増加し、その逆も同様です。ただし、エミュレーターを閉じて再度開くと、データベースにはまだ 4 つの連絡先がありますが、totalContacts 変数は明らかに 0 のままです。

totalContactsデータベース内の連絡先の数を同じにして記憶する方法はありますか?

お時間をいただきありがとうございます。

4

2 に答える 2

2

はい。連絡先の適切な数がわかっている場合は、それを に保存できますSharedPreferences

すべてがAndroidのドキュメントで非常によく説明されています: http://developer.android.com/guide/topics/data/data-storage.html

基本的に、値を保存する場合は、次のように記述します。

SharedPreferences settings = getSharedPreferences("NAME_OF_YOUR_CHOICE", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("numContacts", numContacts);

editor.commit(); // Save the changes

そして、それをロードしたいとき:

SharedPreferences settings = getSharedPreferences("NAME_OF_YOUR_CHOICE", 0);
int numContacts = settings.getInt("numContacts", -1); // if there's no variable in SharedPreferences with name "numContacts", it will have -1 value
于 2013-10-01T05:57:58.643 に答える
1

データを永続的に保存する場合は、Sharedpreferences を使用する必要があります。データをデバイスの RAM に保存し、データを消去するかアプリをアンインストールするまで、データはメモリに残ります。以下のコードを使用します。

//これは、値を初めて取得したときとは、値を取得して保存したいときを意味します。

 SharedPreferences preferences = getSharedPreferences("YOUR_IDENTIFIED_KEY_VALUE", 0);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putInt("Contacts", CONTACTS VALUE);

    editor.commit(); // Save the changes

   // And when you want to get stored values, means when you need yo use that value:

    SharedPreferences preferences = getSharedPreferences("YOUR_IDENTIFIED_KEY_VALUE", 0);
    int contacts = preferences.getInt("Contacts", 0);
于 2013-10-01T06:28:56.973 に答える