On Android you can use a SharedPreferences class to store small quantity of data. Example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
What is the class equivalent to SharedPreferences in Ionic 2? How can it be used?
Ionic 2 has a storage module. The docs are here. It doesn't use SharedPreferences under the hood, but will:
"attempt to use IndexedDB, WebSQL, and localstorage, in that order."
Here is an example from the site I linked:
import { Storage } from '#ionic/storage';
export class MyApp {
constructor(storage: Storage) {
// set a key/value
storage.set('name', 'Max');
// Or to get a key/value pair
storage.get('name').then((val) => {
console.log('Your name is', val);
})
}
}
Related
I need to set some configurations for my android application, like the server IP and Port, which the application should use to communicate. How can I add do it?
I thought of using sharedpreferences. How can I push a sharedpreference file with configurations, before even installing the app.
P.S. I don't want to hardcode the IP and PORT in the code base.
Any suggestions would be helpful.
Thanks
It's not possible. An alternate would be to ship the app with a json config file - put that in the assets folder
And read the contents of the file to prefill values you need.
try {
InputStream inputStream = mContext.getAssets().open(mContext.getPackageName() + ".json");
int size = inputStream.available();
byte[] buffer = new byte[size];
if (inputStream.read(buffer) != size) {
throw new IndexOutOfBoundsException();
}
inputStream.close();
JSONObject jsonObject = new JSONObject(new String(buffer, StandardCharsets.UTF_8));
server_ip = jsonObject.getString("server_ip");
server_port = jsonObject.getString("server_port");
} catch (Exception e) {
e.printStackTrace();
}
}
I would personally put that code in a class that extends Application, so it is called only once.
You CAN NOT push anything before installing. But you can store necessary data in SharedPreferences and retrieve whenever you want. To write/read String data to/from SharedPreferences;
private static final String SHARED_PREFS = "sharedPrefYourApp";
private static final String TEXT = "IP/PORT";
private static final String KEY = "IP_PORT_KEY";
public static void saveData(Context context) {
SharedPreferences sharedPreferences =
context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY, TEXT);
editor.apply();
}
public static String loadData(Context context) {
SharedPreferences sharedPreferences =
context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String text = sharedPreferences.getString(KEY, "");
return text;
}
Another approach would be using something like Firebase Remote Config and then providing the app with configurations dynamically. Think of this approach as the app connecting to a static place; downloads configurations securely and then reacts to those configurations and connects to the end services securely.
If you are trying to make this secure, I would recommend using the Android keychain instead of SharedPreferences - I barely use SharedPreferences (although that's a preference or it depends on security and use case needs).
This is now available in Android via "Managed Configurations"
https://developer.android.com/work/managed-configurations
For some functionality, I want to store PIN which is the user input in settings screen. I want to store that pin locally in mobile until app exists in that specific device.
I have used SharedPreferences to achieve this. Does this the good approach? or any other better approach?
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("1234", YOUR_PIN);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int PIN = settings.getInt("YOUR_PIN", 0);
In our app, we've used PreferenceManager.getDefaultSharedPreferences for our shared prefs. We're now required to use a named prefs instance (for A/B testing).
So now we get the prefs using context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
What I need to do is move all of the stored prefs from the old instance to the new one. Is there a simple solution to do this?
I'm able to get the map of the old prefs but not sure how to write it to the new prefs since writing requires type ("putInt", "putString", etc).
Here's where I've hit a road block:
private void convertToPrivateSharedPrefsIfNeeded() {
SharedPreferences oldPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Map<String, ?> oldPrefsMap = oldPrefs.getAll();
SharedPreferences newPrefs = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
for (Map.Entry<String, ?> entry : oldPrefsMap.entrySet()) {
}
}
I'm guessing that I'm on the right track but not sure what to put in the for loop here
One solution could involving checking the return type of entry.getValue() for each of supported types and call the related method on the editor object. E.g.
for (Map.Entry<String, ?> entry : oldPrefsMap.entrySet()) {
Object current = entry.getValue();
if (current instanceof Integer) {
newPrefs.edit().putInt(...);
} else if (current instanceof ....) {}
}
that should do for the primitive types supported by the SharedPreference.
Alternatively you can try rename the file. The path of the file is
/data/data/your.app.package/shared_prefs/
and your app should be able access that directory directly
Following is the code I used to save SharedPreference:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("deliveryId", obj.get("deliveryId").toString());
editor.commit();
This is not working in some devices, but working in some devices. It is working on KitKat but doesn't work on JellyBean and Lollipop.
Following is the code I used to get the data:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String deliveryId = preferences.getString("deliveryId", "0");
Always gives the default value, i.e. 0, on some devices.
I think default preference creating problem for you try like below for saving SharedPreferences
SharedPreferences preferences = getSharedPreferences("<Pref Name>", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("deliveryId", obj.get("deliveryId").toString());
editor.commit();
to get the data:
SharedPreferences preferences = getSharedPreferences("<Pref Name>", MODE_PRIVATE);
String deliveryId = preferences.getString("deliveryId", "0");
Happy Coding!
hi
i have using shared preference for saving user name and password ,but when my application crashes i lost my data,i need to re login again(Only some crashes i lost the data ),how can i solve this problem ?
SharedData.userInfo = PreferenceManager
.getDefaultSharedPreferences(ctx);
SharedData.userAdd = SharedData.userInfo.edit();
SharedData.userAdd.putString("userEmailAddress", uname);
SharedData.userAdd.putString("userPassword", upassword);
SharedData.userAdd.commit();
I use it like this:
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor prefEdit = sharedPref.edit();
prefEdit.putString("VariableName","Value");
prefEdit.commit();
and it works for me always.