I am using this to write some String to shared preference.
SharedPreferences urls = getSharedPreferences("imagesRemoteUrls", 0);
editorUrls = urls.edit();
editorUrls.putString("url3", imageUrl3);
And i try to pull the url out by.
imageUrl3 = urls.getString("url3","nothing");
I dont know why but it returns "nothing" each time. Even when i log that the url has been put in the preference successfully.
Don't forget:
editorUrls.commit();
after your editorUrls.putString() line!
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
I need to load my json file in my device. It is working perfectly fine in Unity Editor but when I transferred it to my device, json isn't there. Currently using this code for adding data in my json file:
TextAsset file = Resources.Load("Products") as TextAsset;
string jsonString = file.ToString ();
Debug.Log (jsonString);
if (jsonString != null)
{
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
data.products.Add(product);
Debug.Log(data.products[1].code);
jsonString = JsonUtility.ToJson(data);
Debug.Log(jsonString);
}
And this for retrieving:
TextAsset file = Resources.Load("Products") as TextAsset;
string json = file.ToString ();
//string path = Application.streamingAssetsPath + "/Products.json";
string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
It can be use in Unity editor but not in my android device. What seems to be the problem? Very big thanks
As explained here, you can't read file from the Resources folder with anything other than Resources.Load. You must use Resources.Load to read anything placed in the Resources folder.
It doesn't matter if it works in the Editor or not the code below that reads from the Resources folder should not work in any build:
string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);
You don't seem to understand when the Resources folder should be used. This is used to store files that does not need to be changed during run-time. For example, your textures, sound, video files and prefabs. These are not meant to be modified during run-time Also, using it to store default value for a text file is fine.
What need to do is to read the file with Resources.Load("Products") then store it in a string. After you modify it, save to another directory with
Save:
string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
File.WriteAllBytes(tempPath, modifiedJson);.
Load:
string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
jsonByte = File.ReadAllBytes(tempPath);
I made a generic class in another question, to handle that easily so you that you don't even need to use the Resources folder or read the file manually. It handles all the errors too.
From your question, your data is stored in jsonParser class. You should rename that class to actually reflect what you are storing such as PlayerInfo or ProductInfo.
Grab the DataSaver class from here. With your current jsonParser data, you can save and load with the code sample below:
Save:
jsonParser products = new jsonParser();
DataSaver.saveData(products, "Products");
Load:
jsonParser loadedProducts = DataSaver.loadData<jsonParser>("Products");
Delete:
DataSaver.deleteData("Products");
Very easy. That should work on any Platform.
Another simple variant, if you ONLY want to get JSON's text from Resourse:
1.⠀You have file in Resource/Jsons folder, example "simple.json"
2.⠀You use this code:
TextAsset file = Resources.Load("Jsons/simple") as TextAsset;
string json = file.text;
3. Now, you have JSON in string variable! 4. Thats all! Glory to Robots!
I want to save some details on the phone that the application runs, but using a txt extension would make it readable.
Is it possible to write the files as binary and not plain text?something unreadable
You can use sharedpreferences. For example like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
save("PUT YOUR STRING HERE");
Log.e("---> This is it: ", load());
}
private void save(String stringToSafe) // Speichern der Inhalte
{
SharedPreferences shared = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = shared.edit();
String yourString = "The string/value what you want to write into file";
edit.putString("THE_KEY", stringToSafe);
edit.commit();
}
private String load()
{
SharedPreferences shared = getPreferences(Context.MODE_PRIVATE);
String get = shared.getString("THE_KEY", "Error");
return get;
}
For mor you can read here: http://developer.android.com/guide/topics/data/data-storage.html..
Hope this helps!
You can use SharedPreferences, example here
You can use SharedPreferences. But if you want it only in a file, why don't you encrypt it, or encode it and write it to a file? So when you read from it, just decrypt or decode it.
Pretty simple. You can use Base64 encoding and decoding, and there are lot of examples for it.
i want to save a variable to be global variable on all screens i have, for example, for every connect to the localhost i am using 10.0.2.2 so i have to write that ip on every connect,and when i want to try my application on my mobile device i have to go to code and replace all the 10.0.2.2 with my system static ip 192.168.1.101 ,is there any way to say that ip on a global variable? i read that i have to used string on android but i don't know how, any help please
Use SharedPreferences to store and retrieve it: http://developer.android.com/reference/android/content/SharedPreferences.html
Example: http://developer.android.com/guide/topics/data/data-storage.html#pref
public static final String PREFS_NAME = "MyPrefsFile";
//retrieve
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String ip= settings.getString("ip");
//use ip
//store
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("ip", mIp);
editor.commit();
I am retrieving about 7 URL's from a service. I want to be able to write these URL's some where and have my application read from them in another activity.
The thing that makes this tricky is the URL's change every week. So i would need to overwrite the current URL's. I don't want to make the url's stack up on top of each other where they never overrite and by the end of a month there are 24 unused URL's.
What and how is the best way to do this?
Use SharedPreferences!
lol here is a sample:
public void SetUrls(String url[]) {
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("url0", url[0]);
editor.putString("url1", url[1]);
editor.putString("url2", url[2]);
editor.putString("url3", url[3]);
editor.putString("url4", url[4]);
editor.putString("url5", url[5]);
editor.putString("url6", url[6]);
editor.commit();
}
public String[] getUrls() {
SharedPreferences settings = getSharedPreferences(DEALSPOTR_PREFS, 0);
String url[] = new String[7];
url[0] = settings.getString("url0", "default");
url[1] = settings.getString("url1", "default");
url[2] = settings.getString("url2", "default");
url[3] = settings.getString("url3", "default");
url[4] = settings.getString("url4", "default");
url[5] = settings.getString("url5", "default");
url[6] = settings.getString("url6", "default");
return url;
}
it really depends on your client implementation, you can store them in sqlite, or in local cache or shared preferences. Android allows apps to have a small cache.
As you store your urls you can timestamp them and check if they have expired and stuff.
Refere to the docs on android Data Storage facilities.