I'm making an Android application and want to create a "Favorites" list for some objects in the app. I wanna make the list accessible and editable in all my activities and I can't really figure out the best way to do this.
Shared preferences? Writing a small txt file to the device? What's the fastest way to do this?
Thanks in advance!
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
Then when you want to save, convert your array into String:
ArrayList<Type> yourData = new ArrayList<Type>();
String dataStr = new Gson().toJson(yourData);
//put this dataStr in your shared preferences as String
To retrieve and convert back to an object is also simple:
String str = "";
//you need to retrieve this string from shared preferences.
Type type = new TypeToken<ArrayList<Type>>() { }.getType();
ArrayList<Type> restoreData = new Gson().fromJson(str, type);
If you want to create a Favorites list, use a SQLite Database.
There's really only four ways to store data.
Shared Preferences
Databases
Local files
Remote Server - Slowest since it depends on network connection, so let's skip this.
Between the remaining 3, SharedPreferences is a great option when used to store a single value. However, it's not a good option for storing a Favorites list, mainly because you can only store a single String.
You can still store it by combining all items in your list into one string, then splitting it each time. However, as your Favorites list gets larger, this single long String will too. Splitting and combining all the time isn't efficient.
SharedPreferences is still a decent option if you only have to store the Favorite's list, but since you want to edit it too, it becomes a less attractive solution.
Local Files and Databases are the better options, however local files require you to read in the file each time you want to use it. This process of reading and writing to a file isn't as efficient as using a Database, especially if you want to edit. For example, let's say you want to remove an item from the middle of your Favorite's list. This would require you to read in the file, edit it, then write the change into the file again. Not too pleasant when compared with the ease of the final solution.
Databases are the best option for this, mainly because it's designed to manage data. You can create a single Favorite's table and add each item as it's own individual row. Fetching the entire table becomes quick and easy. Fetching a single item becomes quick and easy. Adding a new item or removing a new item is also quick and easy.
Related
I have an app that generates objects of a class, let's call it X, that is Serializable. I want the user to be able to occasionally save or delete objects of X from his/her list of favorites (a list that can go up to 100 objects).
What is the most appropriate way to persistently store the list of favorites?
In SharedPreferences, storing the whole list as a JSON String
In an SQLite database:-
Storing one item per object, as BLOB's
Storing one item per object, as JSON Strings
In a custom file, storing the whole list as a JSON String
Some other way?
My thoughts are:
Because adding and removing favorites will be occasional, and the list is small, I probably don't need the advantages of a DB when it comes to searching fields in large amounts of data. So I am inclined to maintain a local ArrayList, add and remove items from it, and save it to SharedPreferences (option 1).
It seems odd to save a key-value pair holding an entire list as a JSON String, I'm afraid I might be unaware of some sort of limitation.
Is there a limit to the size of the String I can store in SharedPrefferences?
Is it too problematic that I add or remove objects from my local ArrayList and then save the whole list?
I am agree with your first approach because of It's manage easily and need small storage space.
I have this kind of data. This can be or don't be an array. Just for easy reference.
ArrayName = Array1, Array2, Array3
Array1 = abc, cde, fgh
Array2 = abc, cde
Array3 = abc, cde, fgh, ijk, lmn
So, what are the best method to store this kind of data.
If I want to
Add or delete Array1 and all things inside
Add or delete item in Array2(eg. adding fgh or remove cde)
Methods I discovered:
SharedPreference Android Shared preferences example
Arrays
SQLite Android SQLite Example
Text file
Please share the pro and cons of why you choose the method.
Please also share if there are better ways to store this kind of data.
Kindly edit this if you found a better link or sample for other to reference.
Here are pros and cons for each solutions:
1) SharedPreference
You save simple key-value pairs here. So it is very hard to save array and complex structures in SharedPreference. So the solution will not work with arrays and arrays of arrays. It will be extremely(but not impossible) difficult to achieve what you want.
2) Arrays
Absolutely not! It is memory storage, so when you close app, or on process death, you will lose all data
3) SqlLite
I would add to this other Databases for android, like Realm.
Good solution. It is structured storage for collection of data. It will be very easy for storing/retrieving data when it is structured as rows. Furthermore you can delete rows easily. You don't have to read whole structure (other arrays) when you need particular row, or particular array (table in this case)
4) TextFile
I don't recommend to store in a text file, but it is possible to do so, you can serialize those arrays to text file, and deserialize. But every time you have to do this, and to read whole structure and parse it even if you want only e.g. Array2. It can be slow when your data becomes bigger.
It's incredibly hard to give advice with such vague requirements, you apparently have data structured as an array of arrays of strings, and you want to store it persistently on Android - and that's basically all we know.
In addition to the solutions mentioned, I would consider using GSON to store this as JSON to disk. While read/write may not have optimal performance, it's very easy to model documents with things like arrays of arrays, and we have no way of knowing your performance requirements vs ease of use.
class MyData {
public List<List<String>> data;
}
If you then have a MyData object, you could simply serialize it to a string, which could be written to a file on disk:
String json = new Gson().toJson(myData);
This would produce something like
{
"data": [
["abc", "cde", "fgh"],
["abc", "cde"],
["abc", "cde", "fgh", "ijk", "lmn"]
]
}
which could easily be written to disk using e.g. standard File and BufferedWriter. You can then read it back and deserialize using:
MyData myData = new Gson().fromJson(json, MyData.class);
I am currently creating an android application. This application should allow users to enter a RSS feed URL and save it as a preference. I know how to save basic preferences (Strings, booleans...) using a key/value attributes. My problem here is I want to save as one preference the URL of the RSS feed and the name of the website (e.g http://rss.cnn.com/rss/edition.rss --> CNN top stories).
So in this case a single preference is composed with 2 strings and I don't know how to do that.
I found a JSON module making possible to save objects as preferences but I would like to avoid using any modules for this app.
Is it possible to do what I want without external modules and if yes, could you please help me with this issue ?
I feel like you are overthinking this. Instead, consider this approach:
String rssUrl = "someUrlHere";
String rssWebsite = "Some website name here";
//Now, you can use a delimiter before storing your two values
String rssUrlAndWebsite = rssUrl + "," + rssWebsite;
//Now you can store this using one key.
//When you want to read them out, you can use your key to get the value and simply split using the delimiter and there, you will have two values!
I hope this helps;
Alternatively, you could store the two values in a table!
I need to work with a persistent String Array (n Rows, 1 column).
* On first running the app, the String Array needs to be created empty.
* On subsequent app executions the Array will be populated from a File and the contents need to be available throughout the rest of the app.
* As the app is executed, the Array needs to be able to 'grow' in row count
* As the app is executed, the Array rows need to be able to grow in length
* The user will have the option to Clear the Array of previous entries.
* At the end, the String Array contents will be written back to a File.
I find a lot of references to Putting and Getting from an existing SharedPreferences String[] but, in the newness of my Android development, I am struggling with how to proceed.
EDIT Follows...
The data itself suggests using an Array
Example:
MAIN ST. F55 63 KY08:57 12142015--------KY11:24 12142015345TMH KY13:57 12142015
MAIN ST. F56 WYE123 IN08:57 12142015--------KY11:24 12142015--------KY13:57 12142015
1ST ST. F57 --------KY08:57 12142015--------KY11:24 12142015789FPF KY13:57 12142015
1ST ST. F58 456FPF KY08:57 12142015998FPF KY11:24 12142015--------KY13:57 12142015
1ST ST. F59 789TTM KY08:57 12142015--------KY11:24 121420151234DG KY13:57 12142015
I first need to have this data in a File
Then in one GUI I check for the existence of the file.
If one exists, fine
If none exists, I create one.
Then, in subsequent GUI's, I must check for the existence of parameters
If they do not already exist, add them to the existing data lines.
If they already exist, notify the user
And so on and on.
Then when all of the current 'pass' data has been collected via multiple, separate GUI's, I have to write out the whole data-set into the file.
My reason for thinking that I need a SharedPreference approach is the need to find and check data from GUI to GUI as the user progresses through the app.
If that 'belief' is wrong, I am open to better approach suggestions.
EDIT 2 follows....
On further study of web references, I am beginning to think that perhaps the best approach for this data and how the data needs to change might be to use a SQLite approach. Any ideas about this?
Any assistance/suggestions you might have would be greatly appreciated.
i would discourage you from using sharedpreferences for anything else than preferences. means things that change rarely - really rarely and are really lightweight. do not put much data in there. less is better. the data structures underlying sharedpreferences are not a database.
another note. it is not a string list, but it would be a string set. sets are not necessarily ordered, nor do they necessarily keep their order. means - it is not rows. its a collection of strings that can come back in any fun order (usually there is some, but that depends on the implementation which i do not know)
now you could go and make your own list, your own data structure, save it into a string and read it out, use json to do exactly that or something similar, or better - use a database, which would exactly do that.
http://developer.android.com/training/basics/data-storage/databases.html
explains it, but as you'll see its something that might take some time.
now dont get me wrong, but i have to warn you about the following approach. it is valid, but has many problems and is far from thread safe. it will not be a problem as long as you only open it from the ui thread and do not keep anything in memory to cache - if you do it will create lots of problems.
your problem of adding a line and clearing can be solved by using a file. just a simple file
look here
http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
the change is to append when writing:
openFileOutput("filename", Context.MODE_APPEND);
see the context mode? now you can basically just write one line and append every time.
if you wanna clear the file, just deleteFile("filename")
this is as said not threadsafe, but can be a viable option if used carefully.
Please follow this step to achieve what you want with sharedPreference
create the class Parent for SharePreference
Create your empty Array
Convert Your empty array to String and put it on SharedPreference
to call your empty array from sharedPreference
Call your sharedPreference using your key
Convert the String to array
You get your array from the sharePreference
Hope it helps, and maybe this link will help you :
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
You can use my open-source library called prefser, which solves this problem and uses SharedPreferences and Gson under the hood. It's basically wrapper for default Android mechanism.
You can use it in the following way:
Prefser prefser = new Prefser(context); // create Prefser object
prefser.put("key", Arrays.asList("one", "two", "three")); // save array of Strings
String[] value = prefser.get("key", String[].class, new String[]{}); // read array of Strings
For more information check repository of the project, tests and README.md file.
Link: https://github.com/pwittchen/prefser
Please note, SharedPreferences have some limitations and shouldn't be used for storing large amount of data. If you expect a lot of data, consider using SQLite database or another type of database (e.g. with NoSQL or similar approach if you strive for simplicity).
OK, based on the data, how it needs to be manipulated and the pros and cons of using a SharedPreferences approach, I have decided to go with a SQLite approach.
With that approach I should be able to readily check:
* if the necessary table exists (if not create it)
* if the necessary Field1 + Field2 exists (if not create a new record)
* and I will be able to modify the record's Field3 contents as needed
Then when the user's actions are complete I can convert the SQLite table 'records' into strings and write them out as a File and then either DROP or PURGE the associated SQLite table (until needed next time).
I sincerely appreciate all of your suggestions.
Thank you.
I'm currently trying to think of the best way to program an app which simply has text and images that update every day to different content. Would the best way to do this be to store all of the items in an array and then call upon each according to the phone's clock? Or is there a better or simpler way of doing this?
If you need to know I'm using Eclipse to program the app.
You could have the app check for updates each day or you could make a mobile website and use a webview to display the site ,and just update the site daily
Since you are using text and images, I would recommend storing them in your app's SharedPreferences. These keep data stored that your app can easily access to view or change. You can store text and bitmaps easily. For text:
SharedPreferences prefs = getSharedPreferences("MySharedPreferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferences = prefs.edit();
String firstString = prefs.getString("MyFirstString");
//check if firstString has changed on the server
//for example, set a new String that you retrieve from the server to firstStringMaybe
if (firstString != firstStringMaybe) { //meaning you need to update firstString
prefs.putString("MyFirstString", firstStringMaybe);
prefs.commit();
}
Bitmaps storage is much more complicated, because you need to first Serialize the bitmap, then store it as a String. This probably means creating a new class that contains the bitmap object and implements Serializable. There are many examples available for how to do this:
http://www.johnwordsworth.com/2011/06/serializing-and-de-serializing-android-graphics-bitmap/
android how to save a bitmap - buggy code