We have an app in which we have few Array list defined as below
public final static ArrayList<String> Arraylist1= new ArrayList<String>(){{
}};
public final static ArrayList<String> Arraylist2= new ArrayList<String>(){{
}};
public final static ArrayList<String> Arraylist3= new ArrayList<String>(){{
}};
We are updating this array list in between whenever network is available.So it will be like synchronizing the app.Problem we face now is, each time when the app starts it will initialize the array-list and waits for the first synchronization. Is there a way to store the updated array-list locally so that even the synchronization wont happen because of network unavailability, it wont effect the app functionality.
you can make something like this
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
and after you just nead to read the values and update the server...
Or you can store the in a file and when have connection to the internet upload
It depends on what kind of data you deal with. If its lots and heavy data i wouldn't prefer sharedPreferences.
best practice will be saving that data in Sqlite database and retrieving back when required.
another approach is to make the arraylist static like you have done. that will keep values for certain period of time. and will be faster than shared preferences or Sqlite DB to read and write. but you cant count on static variables. their lifetime depends on GC.
You have to store locally what you need, and in case of network unavailability you use the local "older" version.
The main possibilities are 3:
Shared Preferences: file that can be shared among apps or private and it is composed with a couple key-value to store data.
SqlLite DB: a normal relational database.
Files, e.g. json files with your own structure. (Here you are completely free)
Related
This question already has answers here:
Pros and Cons of SQLite and Shared Preferences [closed]
(5 answers)
Closed 6 years ago.
For saving the actual alarm, I figured that a small private sql database would be sufficent, I have used it before for saving data aswell. However, I can't help but think that creating a database takes a lot of power So I could use the shared preference file instead, and just use a couple of linked list or something to store a few parameters for each alarm. This would use alot less space.
But this got me thinking, what is actually the preferred way? By that I mean performance, intregrity, security and the amount of work that needs implementing either shared preference file or SQL database.
Here is what I think are the pros and cons:
Shared Prefs - Useful for storing key - value pairs. The data is persisted in a private file. No concept of structured data, no standardised querying. Writing / reading performs a disk I/O operation, so not super fast.
SQLite - Useful for storing structured data. The db is stored as a private file. SQL used for querying. Performance is similar to the Shared Prefs.
I wouldn't use Shared Prefs for any kind of more complex data. If there will be searching performed on the dataset, SQLite is a no brainer. The size of the database depends solely on the amount of data being used. If you are smart about what you store and how you store it, you shouldn't see you database growing out of control.
AFAIK SharedPreferences are always handy to faster access of data and optimized storage.Even code wise its easier to implement.
I'll suggest an idea for your scenario.
For alarm you hardly require 4 properties.
Time
Description
RepeatMode
Snooze
compile 'com.google.code.gson:gson:2.3.1'
Alarm.java
class Alarm{
private String desc;
private Date time;
private boolean snooze;
private int repeat; // 1 - daily ,2- monthly ,3 - yearly ,4 - none
}
Retrieving Alarms
import java.lang.reflect.Type;
Gson gson = new Gson();
Type type = new TypeToken<List<Alarm>>(){}.getType();
List<Alarm> alarms = gson.fromJson(preferences.getString("alarm",""), type);
Adding Alarms
Gson gson = new Gson();
List<Alarm> alarms = new ArrayList<>();
alarms.add(new Alarm()); // adding alarm
String jsonAlarm = gson.toJson(alarms); //coverting list to json and saving back
editor.put("alarm",jsonAlarm);
editor.commit();
I'm trying to create a way to get input from a user and save the string in the string.xml, so that when I launch my Application again, it will be there. Can I use the string.xml or do I have to save it another way?
Can I use the string.xml or do I have to save it another way?
You will have to do something different. The resources can't be changed after it has been compiled.
Have a look at Storage Options to see which way is best for you. The best way will be determined by things such as the type and amount of data you will be storing.
The link I posted sums it up pretty well then you can dig into the structures that you think might work best for your situation. From the link:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
in order to save your strings you can use SharedPreferences
to save your data
SharedPreferences pos;
public String fileName = "file";
pos = getSharedPreferences(fileName, 0);
SharedPreferences.Editor editor = pos.edit();
editor.putString("pwd","your string");
editor.commit();
to get your data
pos = getSharedPreferences(fileName, 0);
String data = pos.getString("pwd", "");
So I'm working on a project like this http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ which let's me to display my database's values to my android application GUI.
I need to save the database values I need to the android internal storage so I can access it even if my application is not connected to the server. Any help?
Thank you
You can write whole json as string in shared prefernces, and then get it and parse it to display in GUI even when device is offline:
String str = json.toString();
SharedPreferences sharedPref = getSharedPreferences( "appData", Context.MODE_WORLD_WRITEABLE );
SharedPreferences.Editor prefEditor = getSharedPreferences( "appData", Context.MODE_WORLD_WRITEABLE ).edit();
prefEditor.putString( "json", str );
prefEditor.commit();
If you chose local sqlite database as your solution, I wrote a lightweight utility for saving your json into a sqlite.
checkout git repo here. https://github.com/wenchaojiang/JSQL
You only need one line of code.
new JSQLite(yourJsonString, yourDB).persist();
Hope it helps
Consider using a local database to cache the server data locally, that is how most apps does it, here is a good tutorial for sqlite on android Android SQLite
If you use only one or few JSONObjects from the server you can use SharedPreferences, it is much easier and faster to edit/update. example
For more about android storage: Android Storage
I'm working on an application that connects to a php-mysql database in our server, instead of saving the result of the query in a file, you should save it (at least that is what I think so) in an internal Android Database (sqlite). There is a lot of information about databases in Android.
With this example you can see how to easily use sqlite and ContentProviders (a cleaner way of accessing data saved in your database.
In order to save correcty an JSONArray in your database i recommend you to use Jackson libraries in order to create objects from JSON making them easier to be saved.
Finally if the amount of information is relatively small you can use SharedPreferences aswell, this way the data can be accessed faster because it's saved in the mobile memory.
Hope it helps :)
//if you have already the json string
String str = json.toString();
//if you want to convert list to json (with Gson):
//foo - will be your list
String str = new Gson().toJson(foo );
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString("pref_json_key", str);
prefEditor.apply();
You can try to use with Realm.io A Simple Example like this:
public class City extends RealmObject {
private String city;
private int id;
// getters and setters left out ...
}
// Insert from a string
realm.beginTransaction();
realm.createObjectFromJson(City.class, "{ city: \"Copenhagen\", id: 1 }");
realm.commitTransaction();
Regards!!!
i am new to android, i searched a lot and couldn't find a satisfying answer; what i need is to save some setting for my application such as
1> language, number of items to display, display/not display images, etc...
which i think is best done using the shared preferences
2> save which data categories to get from the internet...
here is my problem:
i have data divided into category objects with key, name, type, data[]...(data[] is changing all the time and not saved after exiting the application),(key, name, type are final values defined by programmer).
and because there are many categories which the user may or may not want to load(around 25), he/she can choose which categories to display, and these choices must be saved.
i think using shared preferences will not help because of the complexity of the data; i was thinking of using sqlite or xml, not sure which is the best choice keeping in mind efficiency and memory size.
note: i am using a global variable for the category information array, that is because data[] needs to be refreshed automatically every 2-3 minutes and must be available to all activities also efficiency and memory space are an issue.
i will appreciate any advice, thank you in advance.
1> SharedPreferences is the right choice
2> you have multiple possibilities
a) Use the internal storage and use Object Serialization (for simplicity reasons), xml (if you want to exchange the data) or use a own format
b) SQLite is the fastest solution. But you have to do more programming for that
b would be my choice, so create a DB-Object (static or singleton pattern) and write functions for every database task
1) Yes, SharedSettings should help youy. There is plenty information around, but post back if you are lost.
2) I would make a table with all the categories and a boolean value thats says "show" where you can keep if the user wants to show it or not.
Of course it depends on the size of the categories and how much they change, because otherwise you will be updating the database forever.
User shared preference in store your setting,
SharedPreferences sharedPreferences = this.applicationContext.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
//For saving the setting:
//for storing long
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
//for storing string editor.commit();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
//and similarly for int,float etc
//For Retrieving the string:
sharedPreferences.getLong(key, defaultValue); //for long value
sharedPreferences.getSting(key, defaultValue); //for string value
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