Ogen
Ogen

Reputation: 6709

Android database handler retaining a variable

I have a class called DatabaseHandler and it basically handles a database of Contacts. When I open my android emulator, I can add and remove contacts. Then, when I close the emulator and reopen it, it retains the contacts, so the database stores the contacts.

My problem is this. I have a variable in my contact class like so:

public static int totalContacts = 0;

This variable keeps track of the total number of contacts in the database, so when I add a contact it increments and vice versa. However, when I close the emulator and reopen it, the database still has say 4 contacts but the totalContacts variable has remained as 0 obviously.

Is there a way to make totalContacts equal the number of contacts in the database so its remembered?

Thank you for your time.

Upvotes: 2

Views: 201

Answers (2)

Pratik Dasa
Pratik Dasa

Reputation: 7439

When you want to store data permanently, you must need to use Sharedpreferences. It will save your data in device RAM and untill you do clear Data or you uninstall the app data will remain in memory. Use below code.

//This one when you get your value first time, means when you get the value and want to store it.

 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);

Upvotes: 1

Piotr Chojnacki
Piotr Chojnacki

Reputation: 6867

Yes. When you know the right number of contacts, you can store it in SharedPreferences.

Everything is very well explained in Android documentation: http://developer.android.com/guide/topics/data/data-storage.html

Basically when you want to save the value, you write this:

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

editor.commit(); // Save the changes

And when you want to load it:

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

Upvotes: 2

Related Questions