To parse a local JSON file from the assets folder into a ListView, follow these steps:
Load the JSON file using AssetManager:
public static String AssetJSONFile(String filename, Context context) throws IOException { AssetManager manager = context.getAssets(); InputStream file = manager.open(filename); byte[] formArray = new byte[file.available()]; file.read(formArray); file.close(); return new String(formArray); }
Parse JSON using JSONObject and JSONArray:
try { JSONObject obj = new JSONObject(jsonLocation); JSONArray m_jArry = obj.getJSONArray("formules"); ArrayList<HashMap<String, String>> formList = new ArrayList<>(); HashMap<String, String> m_li; for (int i = 0; i < m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); Log.d("Details-->", jo_inside.getString("formule")); String formula_value = jo_inside.getString("formule"); String url_value = jo_inside.getString("url"); //Add values to the ArrayList: m_li = new HashMap<>(); m_li.put("formule", formula_value); m_li.put("url", url_value); formList.add(m_li); } } catch (JSONException e) { e.printStackTrace(); }
Display data in the ListView:
The above is the detailed content of How to Parse a Local JSON File from Assets Folder into a ListView?. For more information, please follow other related articles on the PHP Chinese website!