0

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?

Ali Imran
  • 8,927
  • 3
  • 39
  • 50
jtehlert
  • 11
  • 1
  • 4

3 Answers3

1

You have following options:

  1. use RoboSpice library

  2. 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();
Paritosh
  • 2,097
  • 3
  • 30
  • 42
0

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

Community
  • 1
  • 1
masterweily
  • 736
  • 1
  • 7
  • 15
0

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

SpdyMx
  • 34
  • 5