Reputation: 149
I'm new to android. i wanted to initialize a shared preference. i just need an auto increment id. i search many shared preferences and i cant understand their explanation.
i just wanted a simple initialization of a number.
for example,
key = RemID and initial value of that key is 0.
i want to initialize that at the first time only, not at every launch of my app
and i will be using that value and increment and store it back.
please share some thoughts.
Upvotes: 2
Views: 1600
Reputation: 343
Hi below is may be help for you
private void setShared() {
SharedPreferences records = getSharedPreferences(
LoginActivity.USER_RECORD, 0);
SharedPreferences.Editor prefEditor = records.edit();
int count = nImageUrl.size();
for (int i = 0; i < count; i++) {
prefEditor.putInt(ID + savedPhotosCount, Singleton.instanse.getCustomerID(mCustomerIndex));
prefEditor.putString(FILE_PATH + savedPhotosCount, nImageUrl.get(i));
prefEditor.putString(DESCRIPTION + savedPhotosCount, captionText.get(i));
savedPhotosCount++;
prefEditor.putInt(SAVED_PHOTOS_COUNT, savedPhotosCount);
}
prefEditor.commit();
}
First declare the variable
int savedPhotosCount = 0;
Every time the id was incremented.
Upvotes: 0
Reputation: 318
Try this out
int sharedPrefValue;
then in the onCreate method,
sharedPrefValue=PreferenceManager.getDefaultSharedPreferences(this).getInt("sharedPrefValue", 0);
and then,
sharedPrefValue++;
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("sharedPrefValue", sharedPrefValue).commit();
Upvotes: 0
Reputation: 75427
I'd suggest using the default value parameter of SharedPreferences
's get*
methods.
For example:
SharedPreferences prefs = context.getSharedPreferences("counters",
Context.MODE_PRIVATE);
// increment a counter
int counter = prefs.getInt("counter", 0); // Using '0' for the default value
prefs.edit().putInt("counter", counter+1).apply();
Upvotes: 5