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.
Related
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));
I'm trying to make "add favorites" button in my app. I can send and get value with sharedpreferences properly, but when I restart the app, favorites are empty again. I guess I need override OnPause method, but I couldn't apply properly. I need help, thanks in advance.
PLAYING RADIO FRAGMENT
public static int incrementedValue = 0;
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("radio_link"+ incrementedValue, radio_play_link);
editor.putString("radio_name" + incrementedValue, radio_name);
editor.putString("listener_number" + incrementedValue, listener_number);
//editor.clear();
editor.commit();
incrementedValue++;
}
});
FAVORITES FRAGMENT
final List<String> radio_name_list = new ArrayList<>();
final List<String> radio_link_list = new ArrayList<>();
final List<String> listener_numbers = new ArrayList<>();
for (int i=0; i<PlayRadioFragment.incrementedValue; i++) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
radio_name_list.add(settings.getString("radio_name" +i, ""));
radio_link_list.add(settings.getString("radio_link" +i, ""));
listener_numbers.add(settings.getString("listener_number" +i, ""));
}
...
then I show them in listview
...
for (int i=0; i<PlayRadioFragment.incrementedValue; i++)
After restarting the app (or Fragment), this incrementedValue will be back to what it was initialized with, probably 0, so you won't load anything from SharedPreferences (not entering the for-loop at all).
Try something like
for (int i=0; i<Integer.MAX_VALUE; i++) {
String s = settings.getString("radio_name" +i, "")
if (TextUtils.isEmpty(s))
break;
} else {
radio_name_list.add(s);
}
You probably also want to avoid overwriting the old favorites after the app restart, so you have to set the incrementedValue after loading the favorites like
incrementedValue = radio_name_list.size();
This is happening because on restarting app the variable named incrementedValue gets value once again as 0 and in for loop conditional statement is not full filling and that's why loop is not executing as expected. To resolve this issue you can do one more thing you need to save the value of incrementedValue in shared preference as well and in for loop testing statement get the updated value from shared preference. Hope that helps you
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();
i wish to, in one activity, put strings in the sharedpreferences, so then, in another activity, i get those strings, put them in a array and display them sequentially. I managed to do this, but i don`t have any idea how can i delete one specified string when asked. These strings will just be scattered on the shared preferences,and i dont know how to keep track of them. I can pass this unique int id to each element. I tried to use LinkedList, but i cannot pass this kind of structure as a shared preferences. I did not managed to make Gson work also. Please help.
Method that gets the string and put on shared preferences:
public void makefavorites(String[] a, String[] b, int id)
{
int idfinal = id%10;
idfinal = idfinal+1;
a[idfinal] = b[idfinal] +"\n" + "\n"+ a[idfinal];
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
Editor edit = prefs.edit();
int temp = prefs.getInt("favorites_size", 0);
edit.putInt("favorites_size", temp+1);
edit.putString("array_" + prefs.getInt("favorites_size", 0), a[idfinal]);
edit.commit();
refreshfavorites();
}
Method that gets those strings, put on array and display it:
public void refreshfavorites()
{
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
//GETS THE ARRAY SIZE
int size = prefs.getInt("favorites_size", 0);
String[] array = new String[size];
for(int i=0; i<size; i++){
array[i] = prefs.getString("array_" + i, null);
}
}
you have to use editor.remove method to delete specific value from arraylist..
public void removeArray(String[] list)()
{
SharedPreferences.Editor editor = mSharedPrefs.edit();
int size = list.length();
for (int i = 0; i < size; i++) {
editor.remove("favorites_size"+i);
}
editor.commit();
}
i hope its useful to you..
My objective is to save a field entered in an EditText when the user clicks on a button; in this case it's an IP address. The idea would be to show a list of all valid entered IPs when the user focuses on the EditText, similar to saved searches.
I found this useful piece of code. I need a bit of help explaining it. The code runs putString of all the elements in the String[] array which I think is a collection of all the submitted fields in EditText. How do I create this array if only one field is getting added at a time? I need an explanation of what is happening below.
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i = 0;i < array.length; i++){
editor.putString(arrayName + "_" + i, array[i]);
}
return editor.commit();
}
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
As per your requirement and the code you referenced, I get the following idea:
Untested for erratas:
public boolean saveoneData(String oneTimeData, String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+"_size", 0); // For the first time it gives the default value(0)
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key+ "_" + size, oneTimeData);
editor.putInt(key+"_size", ++size); // Here everytime you add the data, the size increments.
return editor.commit();
}
public String[] loadArray(String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+ "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(key+ "_" + i, null);
return array;
}
But I usually don't use the sharedpreferences for large storage of data because it could make data creation, retrieval and data modifications difficult as the data increases. Hope this is what you want.
Once you collect all EditText values in one String[] array or List<String> or Set<String>;
You don't need to save each array value as separate key-value pair in the SharedPreferences. There is much simpler way to save, which is create Set<String> and save them all values under one key:
editor.putStringSet(arrayName, new HashSet<String>(Arrays.asList(array));
For retrieving you can retrieve them as Set<String> in same manner:
Set<String> ipsSet = sharedPrefs.getStringSet(arrayName, null);
What is happening in the code you posted:
Each value of String array is saved individually under unique key and the size of the array, likewise.
Similarly later each item is retrieved moving in the range 0 to the saved size of the array, which is retrieved at first place from the SharedPreferences