× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Reading json file from assets in Android

Arnav Gupta
Dec 02, 2015
<p>file: assets/locations.json</p> <pre><code class="language-json">{ "locations" : [ { "key": "fence1", "name": "Some geofence", "lat": 77.12332, "lng": 23.456, "radius": 1000, "audio_file": "my_tune.mp3" } ] }</code></pre> <p>file: src/main/java/com.package/MainActivity.java</p> <pre><code class="language-java">public ArrayList&lt;MyLocations&gt; loadJSONFromAsset() { ArrayList&lt;MyLocations&gt; locList = new ArrayList&lt;&gt;(); String json = null; try { InputStream is = getAssets().open("locations.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } try { JSONObject obj = new JSONObject(json); JSONArray m_jArry = obj.getJSONArray("locations"); for (int i = 0; i &lt; m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); MyLocations location = new MyLocations(); location.setLat((float) jo_inside.getDouble("lat")); location.setLng((float) jo_inside.getDouble("lng")); location.setKey(jo_inside.getString("key")); location.setRadius(jo_inside.getInt("radius")); location.setName(jo_inside.getString("name")); location.setAudio_file(jo_inside.getString("audio_file")); //Add your values in your `ArrayList` as below: locList.add(location); } } catch (JSONException e) { e.printStackTrace(); } return locList; }</code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus