how to save json array to android internal storage - android

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!!!

Related

Android storing array list locally and using it

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)

save strings to string.xml, Android

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", "");

How to save a couple of strings to internal storage in android?

I'm trying to develop a simple notepad on android. But I don't know how to save my notes(strings) to internal storage(or to an SQL database if it's faster). if I used internal storage would I be able to save a couple of strings and get them back? I'm a beginner to mobile application development and this is my first project. so I'd really appreciate it if you could show me a sample code so I can learn from it. Thanks!
A database is an option, therefore you'll definitively have to read the follow page, that helped me a lot. There is also some sample code in it.
http://www.vogella.com/articles/AndroidSQLite/article.html
In paragraph 9.7 is the full code for adding, editing and deleting records...
An other option is saving the string in an .txt file and save that on the storage. Than this might bring you further:
Write a file in external storage in Android
Good luck!
You can save it in shared preference if it is not too big.
To store:
SharedPreferences sharedPref = getSharedPreferences("SomeName", Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putString("String1", value); // value is the string you want to save
editor.commit()
To retrieve:
SharedPreferences sharedPref = getSharedPreferences("SomeName", Context.MODE_PRIVATE);
String retrievedString = sharedPref.getString("String1", defaultValue);
"SomeName" ---- the preference name
"String1" ---- key for the string you want to store/retrieve
defaultValue ---- in case the key is not available, this is the retrieved string

Save JSON from url for local development

I have an android app that downloads json data from a url, parses and then displays it.
Unfortunately, I will be away from internet for awhile, but would like to continue to work on the app.
Is there a way that I can save that data for offline use?
Essentially, is there a way I can hard code a JSONObject to use the data found at link
So that I will have it locally?
You have following options:
use RoboSpice library
use android volley library
Both above libraries have caching capability. Conditionally you can invalidate cache to retrieve updated data.
Use shared preferences to store JSON string and update that as and when required.
To store data:
SharedPreferences settings = getApplicationContext().getSharedPreferences("PREF_NAME", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("strJSON", "" + strJSONfromServer);
editor.commit();
To retrieve data :
SharedPreferences settings = getApplicationContext().getSharedPreferences("PREF_NAME", MODE_PRIVATE);
String strData = settings.getString("strJSON", "");
To clear data :
SharedPreferences settings = getApplicationContext().getSharedPreferences("strJSON",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove("strJSON");
editor.commit();
if you have http server installed in your machine , you can save that json data as text file, and access it from the device with the url: "http://10.0.2.2:PORT_NUMBER"
another solution, no need for http server, you can save the data as text file and access it from your device, as explained in this answer:
Reading a simple text file
Edit:
simpler way would be just save the data in a String:
String stringJson = "{\"Baseball\":[{\"Opponent\": ... "
(be aware you will have to escape the characters with \")
to parse the json data, all you need to do is
JSONObject jsonObject = new JSONObject(stringJson);
Another option in to store your json in file under the assets directory. Then you will be able to acces it like any other file in your application:
http://developer.android.com/reference/android/content/res/AssetManager.html

saving the values in database of sd card in android

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

Categories

Resources