Android equivalent of NSUserDefaults in iOS
Asked Answered
A

1

112

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.

Ariadne answered 27/8, 2010 at 12:49 Comment(0)
A
229

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.apply();


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

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

Ariadne answered 27/8, 2010 at 14:17 Comment(6)
this is the way to go for storing very simple things, its simple and straight to the pointChopping
I fixed the error in the code (was calling the non-existent getPreferences, not getSharedPreferences).Houseless
Update 2015: Android recommends the use of apply() now over commit() because apply() operates on a background thread instead of storing the persistent data immediately and possible blocking the main thread.Letitialetizia
Is there a way to access this SharedPreferences from jni code?India
To get the 'context' from within AppCompatActivity, you can use getApplicationContext()Ferraro
An Activity is your context. So use 'this' as context in Activities. In Fragments you'll want to use requireActivity().Diapositive

© 2022 - 2024 — McMap. All rights reserved.