Hello Everyone,
This time while working on creating a list for the recycler view, i tried loading it from a json file which i downloaded from internet.
Approach :
- Place your json file in your Assests folder.
- Create a string and start adding the contents of your json file into this string.
- use this string as argument while declaraing your JSONArray.
See, its really simple.
Let me give you example on how to code this approach and get it working.
1 2 3 4 5 6 |
try { String JsonString = loadJSONFromAsset(); JSONArray jsonArray = new JSONArray(JsonString); } catch (JSONException e) { e.printStackTrace(); } |
Now the Function loadJSONFromAsset();
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public String loadJSONFromAsset() { String json = null; try { InputStream is = getAssets().open("my_json_file.json"); //Replace "my_json_file.json" with the name of your json file int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); return null; } return json; } |
That’s it !
Now you have got your JSONArray and you can use it simply as per your requirements.
Keep coding and keep sharing. : )