Android equivalent of NSUserDefaults in iOS

AndroidIosNsuserdefaultsCode Translation

Android Problem Overview


I'd like to save some simple data. On the iPhone, I can do it with NSUserDefaults in Objective-C.

What is the similar command here in Android?

I'm just saving a few variables, to be reused as long as the application is installed. I don't want to use a complicated database just to do that.

Android Solutions


Solution 1 - Android

This is the most simple solution I've found:

//--Init
int myvar = 12;


//--SAVE Data
SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);  
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("var1", myvar);
editor.commit();


//--READ data    	
myvar = preferences.getInt("var1", 0);  

Where 'context' is the current context (e.g. in an activity subclass could be this).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchristian MullerView Question on Stackoverflow
Solution 1 - Androidchristian MullerView Answer on Stackoverflow