SharedPreferences, doubles and arrays in Android - android

I have a user to insert 10 numbers that will be stored in an array. From this number the average is calculated and stored in a double.
Now I want send the array and the double to another activity but I don't see any option when I type editor.put.
How can I do that?
public int[] number = new int[10];
public double avg;
...
SharedPreferences.Editor editor = myPrefs.edit();
editor.put...
editor.put...
editor.commit();
Thanks,
Marco

If you only need to pass these values to another Activity and not hold on to them for longer term use, just embed them as an extra in the Intent used to start the other Activity.
Just use your own String keys which are known to both Activity classes and call:
putExtra(YOUR_INT_ARRAY_KEY, yourIntArray)
putExtra(YOUR_DOUBLE_KEY, yourDoubleVal)

Maybe you can just use JSON if that isn't too much overhead for you.
See this example:
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < number.length; i++) {
jsonArray.put(i, number[i]);
}
...
editor.put("YOUR_KEY", jsonArray.toString());
...
JSONArray array = new JSONArray(myPrefs.getString("YOUR_KEY", ""));
array.get(i);
...
Here the Link to the API. JSONObject may also be worth a look at:
JSONObject
JSONArray

I solved the problem in this way. It works well.
public int[] number = new int[10];
public double avg;
...
SharedPreferences.Editor editor = myPrefs.edit();
editor.putFloat(AVERAGE, avg);
StringBuilder intArrayToString = new StringBuilder();
for(int i=0; i<number.length; i++)
{
intArrayToString.append(number[i]).append(",");
}
editor.putString(INT_TO_STRING, intArrayToString.toString());
editor.commit();

Related

How to save/load arraylist that contains double values?

I have 5 arrayLists created that have double values
public ArrayList<Double> arrayList1 = new ArrayList<Double>();
public ArrayList<Double> arrayList2 = new ArrayList<Double>();
public ArrayList<Double> arrayList3 = new ArrayList<Double>();
public ArrayList<Double> arrayList4 = new ArrayList<Double>();
public ArrayList<Double> arrayList5 = new ArrayList<Double>();
I am trying to save them after the user enters values in an editText and clicks a submit button
if(spinnerPosition==1){
arrayList1.add(Double.parseDouble(enterText.getText().toString()));
}
Then I would like to load arrayList and use the values inside arrayList to calculate an average. I have the method to calculate the average, just need to know how to load arrayList to calculate average every time a new value is entered
public String arrayList1AverageResults(){
double sum=0.0;
if(arrayList1.size() > 0){
for ( int i=0; i < arrayList1.size() ; i++) {
sum += arrayList1.get(i);
}
arrayList1Avg = sum / arrayList1.size();
}
return arrayList1Avg;
}
There are a number of ways to persist the data when the App close.
You could serialise them to a file.
You could serialise them to shared preferences.
Save ArrayList to SharedPreferences
Or probably must better store them to a database (Android has various ways to store them to a database like SQLite
Reference https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
Tutorial for one method https://www.tutorialspoint.com/android/android_sqlite_database.htm
Or the more "Android" way with https://developer.android.com/training/data-storage/room/
I would persist the ArrayList using SharedPreferences using GSON library like so:
Save
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList1);
editor.putString("ARRAY_LIST_1", json);
editor.commit();
Read
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString("ARRAY_LIST_1", "");
arrayList1 = Arrays.asList(gson.fromJson(json, Double[].class));
This is what worked for me
private void saveArrayList1(){
SharedPreferences sharePref= getActivity().getSharedPreferences("ArrayList1",MODE_PRIVATE);
SharedPreferences.Editor editor= sharePref.edit();
Gson gson= new Gson();
String json= gson.toJson(arrayList1);
editor.putString("Array1",json);
editor.apply();
}
private void loadArray(){
SharedPreferences sharePref= getActivity().getSharedPreferences("ArrayList1",MODE_PRIVATE);
Gson gson= new Gson();
String json = sharePref.getString("Array1",null);
Type type = new TypeToken<ArrayList<Double>>(){}.getType();
arrayList1=gson.fromJson(json,type);
if (arrayList1 == null) {
arrayList1 = new ArrayList<>();
}
}

Convert string to an object

I have 3 string list and I want to add all values to menus but it gives error which is "Invalid index 0, size is 0". Briefly, menus is null and how can I add them?
private List<List<Restaurant.Menu>> menus = new ArrayList<>();
ArrayList<String> MenuName = new ArrayList<>();
ArrayList<String> FoodName = new ArrayList<>();
ArrayList<String> FoodPrice = new ArrayList<>();
//I get values in DB. DB is full.
MenusName = tinydb.getListString("MenuName");
FoodName = tinydb.getListString("FoodName");
FoodPrice = tinydb.getListString("FoodPrice");
int restaurantCounter = 0;
int menuCounter = 0;
for (int j = 0; j < MenusName.size(); j++)
{
menus.get(restaurantCounter).get(j).name = MenusName.get(j))
}
Example, I created them for each value, it works but if string is long, it enforces app and I wait 10 sec. for this process. I need efficient way. Thanks in advance.
menus.get(resCounter).add(new Restaurant.Menu());
menus.get(resCounter).get(menuCounter).foods.add(new Restaurant.Food());
.
.
menus.get(resCounter).get(menuCounter).name = MenuName.get(i));
menus.get(resCounter).get(menuCounter).foods.get(foodCounter).name = FoodName.get(i);
menus.get(resCounter).get(menuCounter).foods.get(foodCounter).price = FoodPrice.get(i);
You seem to be confusing arrays with lists here. Arrays have a fixed size once initialised, Lists don't. You need to add something to your menus list using menus.add(/*Add Menu Object here*/);
You haven't add any values to menus.so the object doesn't contain value at the index 0. This might be a reason.
I couldn't find a solution so I changed structure. I get all strings in restaurants and I used gson to convert them before store them. Also you can use gson for each string. It it same logic.
Gson gson = new Gson();
ArrayList<String> gsonString = new ArrayList<>();
for(int i=0; i<restaurants.size(); i++)
gsonString.add(gson.toJson(restaurants.get(i)));
tinydb.putListString("tinyRestaurant",gsonString);
Convert again...
Gson gson = new Gson();
for(int i=0; i<tinydb.getListString("tinyRestaurant").size(); i++)
restaurants.add(gson.fromJson(tinydb.getListString("tinyRestaurant").get(i), Restaurant.class));

Android Integer Arrays

Hello I am new to Android development and I decided to work with the AndroidPlot library. To create a graph I need to enter in a number array like this
Number[] seriesOfNumbers = {4, 6, 3, 8, 2, 10};
What I need help with is creating that data in my app. My app runs a service once everyday and I want it to collect a certain number and add it to this array. Say for example something like this..
ArrayList<Integer> seriesOfNumbers = new ArrayList<Integer>();
seriesOfNumbers.add(5);
// Save the array
and then the next day retrieve this array and add another number to it and so on. Ive read that I should use SQLite but I am storing only one number each day. I cant create a new Array everyday because i need data from the previous days. What is the proper way to do this? Thanks
Edit:
This is as far as I got
public static void saveArray(Context ctx)
{
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences
.edit();
Number[] list = new Number[10];
StringBuilder str = new StringBuilder();
for (int i = 0; i < list.length; i++)
{
str.append(list[i]).append(",");
}
sharedPreferencesEditor.putString("string", str.toString());
sharedPreferencesEditor
.commit();
}
public void getArray(Context ctx)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
String savedString = prefs.getString("string", "1");
StringTokenizer st = new StringTokenizer(savedString, ",");
for (int i = 0; i < 1; i++)
{
array[i] = Integer.parseInt(st.nextToken());
}
}
What I would like to do is be able to pass an integer through saveArray(Context ctx) and have it added to an array. Then it gets parsed into a string to be stored into shared preferences and then retrieved by getArray(Context ctx) where it gets recreated into an array if that makes any sense. Any help is very much appreciated Note: above code causes FC
Try something like this:
ArrayList<Integer> seriesOfNumbers = existsList() ? loadList() : new ArrayList<Integer>();
seriesOfNumbers.add(5);
saveList(seriesOfNumbers);
You just have to implement the ...List() - methods, maybe by using SqLite.

In shared preferences how to store string array in android application

In my application am using list view in base adapter.
when i click the item its id store in shared preferences string array format. how to save multiple item id in string array format
[1,2,5,6] like this
You can try using JSONArray as JSON is light-weight also, you can create a JSONArray and write it to SharedPreference as String.
To write,
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();
To Read,
try {
JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
for (int i = 0; i < jsonArray2.length(); i++) {
Log.d("your JSON Array", jsonArray2.getInt(i)+"");
}
} catch (Exception e) {
e.printStackTrace();
}
If you are using API 11 then its possible by using putStringSet. Otherwise you may either convert your string array into a single string as mentioned by #hotverispicy or use SQLite database
you can save it as string by ,(comma) seperator and while fetching just use split()
string toPut="";
toPut += "listItem,";
set toPut in your SharePreference and commit()
To get the same in array: get prefString from SharePreference
String[] fetchArray= prefString.split(",");

Storing a String array in the SharedPreferences

I was wondering if it could be possible to save in the shared preferences an array of Strings, in a way that, every time we save a certain String, we store it in that array.
For example I have a list of locations with a certain ID that I want to mark as favorite.
The ideal situation would be, having an array and saving a certain location ID (let's call it Location1) in that array, so next time I want to mark a new location as favorite (let's call it Location2), I retrieve that array (which so far contains Location1) and add the ID of this new location I want to add (Location2).
Android has methods to store primitive objects, but not for arrays.
Any idea in order to do this, please?
This is doable: I was just blogging about it:
SAVE YOUR ARRAY
//String array[]
//SharedPreferences prefs
Editor edit = prefs.edit();
edit.putInt("array_size", array.length);
for(int i=0;i<array.length; i++)
edit.putString("array_" + i, array[i]);
edit.commit();
RETRIEVE YOUR ARRAY
int size = prefs.getInt("array_size", 0);
array = new String[size];
for(int i=0; i<size; i++)
prefs.getString("array_" + i, null);
Just wrote that so there might be typos.
You could make the array a JSON array and then store it like this:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
SharedPreferences.Editor editor = settings.edit();
JSONArray jArray = new JSONArray();
try {
jArray.put(id);
} catch (JSONException e) {
e.printStackTrace();
}
editor.putString("jArray", jArray.toString());
editor.commit();
You can then get the array like this:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
try {
JSONArray jArray = new JSONArray(settings.getString("jArray", ""));
} catch (JSONException e) {
e.printStackTrace();
}
Just an alternative solution that I have used in the past
Write methods to read and write a serialized array. This shouldn't be too difficult. Just flatten the array of strings into a single string that you store in the preferences. Another option would be to convert the array into an XML structure that you then store in the preferences, but that is probably overkill.

Categories

Resources