Edit: sorry I originally read the question wrong
Can I use SharedPreferences in executables?
Yes. If data is of primitive type you definitely should.
How?
From the android developers documentation:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
I posted a similar answer on how to use SharedPrefs here just take note that this use case of SharedPreferences breaks the benefits of the HashMap, which is really fast for finding and getting a value for a key.
One way you could do it is the following:
//if you are running the code inside from an Activity
Context context = this;
SharedPreferences userSharedPrefs = context.getSharedPreferences("USER_NAME_PREFS", MODE_PRIVATE);
SharedPreferences pwdSharedPrefs = context.getSharedPreferences("PWD_PREFS", MODE_PRIVATE);
The method getAll() will return a data structure called HashMap
which works like a dictionary:
For each value stored there is a unique key.
sidenote: By getting them all at once you are kinda breaking the purpose of this data structure but let's continue
Map<String, String> userNameHashMap = (Map<String, String>)userSharedPrefs.getAll();
Map<String, String> pwdHashMap = (Map<String, String>)pwdSharedPrefs.getAll();
then you can do whatever you want with them
want them in a list? (I am assuming your user names are strings by the way)
List<String> userNameList = new LinkedList<>();
userNameList.addAll(userNameHashMap.values());
want to know if there's a password for user john?
boolean johnHasPasswd = pwdHashMap.containsKey("john");
String johnsPass;
if(johnHasPasswd)
johnsPass = pwdHashMap.get("john");
If you want to use the native data storage mechanisms, you are limited to the following
Your data storage options are the following:
- Shared Preferences Store private primitive data in key-value pairs.
- Internal Storage Store private data on the device memory.
- External Storage Store public data on the shared external storage.
- SQLite
Databases Store structured data in a private database.
- Network Connection Store data on the web with your own network server
You should have a look at these official docs from the developers website.
Hope this helps!