This question his perhaps more a request for some advice how to save some data in the best way. I'm doing an app where I tag images from the device with contacts from the ContactsContract in the device by saving the filepath for the image together with the selected contact, and by contact, I guess it's enough to save the ID or the name of that contact?
I need some advice how I should use the FileOutputStream to write this data. Should I, and can I save the strings like "filepath, id" for each row in the file or what's the best way? I also need to search if the filepath and contact is already in the file aswell as be able to tag several contacts to an image. First I thought I could use a file for each image and add all the contacts that are tagged with it, but that is perhaps not a good way to do it?!
Preciate some advice!
EDIT:
If I use Shared Preferences then I could use the contacts ID as a key and the image path as the value? Then I can add several unique ID keys with different values? But I guess, I can't add more than one value to a key?
You need some kind of structured data system.
Have you tried SQLite? - SQLite seems good for the job.
CREATE TABLE `contact`('id' INT , 'contact_id' TEXT, 'image_file_path' TEXT, TEXT, PRIMARY KEY('id'))
You search feature is easy then;
SELECT * FROM contact WHERE contact_id ='1'
I would start here.
Edit:
You can insert the contact details by converting it to jsonstring and put in a sharedPreferences.
Example:
JSONObject obj=new JSONObject();
obj.put("Contactid", 1);
obj.put("ImagePath", "/sdcard/download/a.png");
String jsonstring=obj.toString();
if you have multiple contacts than use json Array Like this
JSONArray array=new JSONArray("ContactDetails");
for(int i=0;i<noofcontacts;i++)
{
JSONObject obj=new JSONObject();
obj.put("Contactid", 1);
obj.put("ImagePath", "/sdcard/download/a.png");
array.put(obj);
}
jsonstring= array.toString();
save contact details in the SharedPreferences like this
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("contactDetails", jsonstring);
editor.commit();
Now get SharedPreference values
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String jsoncontactdetails= sharedPreferences.getString("contactDetails", null);
I hope you know Json Parsing.
Using Database is the best option in this case. Because it is hard to maintain each file in the internal storage and it also consume some processing time. Best is the contact the image path of the contact in the database .
Related
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'd like my app to allow a single user to create a profile that is accessed every time they run the app. The user's profile contains a String entry and five int entries. I've thought about using an SQLite database to store the info between sessions, but it seems like overkill since I'd only need one row in a single table to store the data. However, I'm not sure if it's possible to use SharedPreferences on a String type of data.
Can anyone provide some insight into this issue please? Thank you!
Yes you can use SharedPreferences.
To write
Editor editor = getSharedPreferences("file_name", MODE_PRIVATE).edit();
editor.clear();
editor.putString("pref_name", myStringValue);
editor.commit();
To read back
SharedPreferences preferences = getSharedPreferences("file_name", MODE_PRIVATE);
String myStringValue = preferences.getString("pref_name", "default_value");
Regards.
can i store two or more values with same key using SharedPreferences in android? If no, please tell me how to store values of username, first name, password etc when many users register in registration app?
Ex:
person A registered with username="john12", first name="john" and DOB="06/06/2000".
person B registered with username="arun89", first name="arun" and DOB="08/11/1989".
Now, I want to store these values in SharedPreferences and retrieve them later. Is it possible using SharedPreferences? If not, Please tell me how to do in other way.
Thank you in advance.
I woud consider creating a JSONObject and add the fields you want to store as a key:value pair.
json.putString(key, value);
You can then store the json object in it's string representation with json.toString() and restore it later with
JSONObject jo = new JSONObject(jsonString);
String value = jo.getString(key);
JSONObject also offeres different data types beside strings.
It really depends on how much data you want to store. Depending on that I would choose SharedPreferences or a SQLite implementation.
You cannot store these values directly (as ones added latter will overwrite previously added) but you can always store Parcelable and put your data into it
For your case it is better use SQLIte database.But if you want to use shared preference it is still possible.You have to use a key with additional index to remember different user like
UserName1:arun
UserName2:john
You have to remember the total number of user.Then can maintain all of them.you can also use other data structure like hashmap to maintain data for the shared preference.
I dont't think it is possible, as you don't know the number of users.
You could try to separate the users with commas, but that's lame.
You should consider using SQLite database.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Then you have to store a array List of user objects first create a class userInfo then create a array List type of userInfo then store the data in this list and put a serialize-able object in SharedPreferences.
You can also store them on a single key called "registers" as string. Concatenate each register to preference. Put ";" (or any other characther you want) between each register. Then parse the string and use the values.
Key: registers
Value: "username=john12, first name=john, DOB=06/06/2000;username=mike12, first name=mike, DOB=06/07/2012"
Using split method of String will give you a list of registers as String.
registers.split(";");
Splitting again with "," will give you properties of each register.
I created an app in which users can add various markers on google maps using overlays. I want the app to save the overlay when the user creates it so that when they re-open the app later the markers will still be present.
Currently anytime the app is re-opened the created markers are gone. I have searched the internet and have not gotten a clear understanding of how to save my markers/overlays offline for later use.
As mentioned, you need to use some persistent storage. Perhaps, database would be an excess in your particular case (if you simply need to save a bunch of longitude-latitude pairs), and Shared Preferences would fit your needs. If you rarely need to read/store this data, then putting JSONArray as a String to Shared Preferences would be the simplest (in terms of reading and extracting data) solution:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
JSONArray jsonArr = new JSONArray();
JSONObject json;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
json = new JSONObject();
json.put("lat", user_markers.get(i).getLat());
json.put("long", user_markers.get(i).getLong());
jsonArr.put(json);
}
editor.putString("markers", jsonArr.toString());
editor.commit();
If you need to read/store this data a bit more often, then you may assign ids/indexes to separate SharedPreferences's values, but this may require more complicated extraction method. For example:
SharedPreferences.Editor editor = getSharedPreferences("name", 0).edit();
int id;
for (int i = 0; i < user_markers.size(); i++) { // here I assume that user_markers is a list where you store markers added by user
id = user_markers.get(i).getId(); // some Id here
// or simply id = i;
editor.putString("markers_lat_" + id, user_markers.get(i).getLat());
editor.putString("markers_long_" + id, user_markers.get(i).getLong());
}
editor.commit();
After all, you should consider using database if you plan to store big amount of data or data of complicated structure.
It just an idea, but you can save your markers in database and when you reopen your map just query database and put it on the map again...
You should use some persistent storage. SQLite would probably be the best option here. Overlays have their lat and lng. Just get them and whatever data you need along with them and put all these in the SQLite database. Then on Activity start get the points from database and show them on the map.
Use a SQLite database to save the user data. They are simple and for a large amount of data they are better than SharedPreferences.
More Info
Example
I am developing a small android application in which I have to save the values in database.
How should I pursue?
Do you want to use database or shared preferences for your applications? If you are looking for shared preferences, the following is a piece of code that demonstrates how to store and retrieve a username and password.
//Saving the username and password
editor = getSharedPreferences("SampleApps", 0).edit();
editor.putString("userName", "David");
editor.putString("password", "Bravo");
editor.commit();
//Retrieving username and password
SharedPreferences sharedPreferences = getSharedPreferences("SampleApps", 1);
String userName=sharedPreferences.getString("userName", null);
String password=sharedPreferences.getString("password", null);
I hope this is what you are looking for.
In Android, you can use both Shared preferences and database to save the data permanently in the device.
By using Shared preferences, the data are saved in XML format. You can find the data in /data/data/yourPackage/shared_prefs. It is a simple format recommended to have variables.
For more complicated structure, you should use the database that comes with Android, which is SQlite. You can find the database in /data/data/yourPackage/databases SQL sentences could be used to create tables and add values. For easier use, an adapter is recommended.
For more information, there is very good tutorial in the Android official page:
http://developer.android.com/guide/topics/data/data-storage.html