Home  >  Article  >  Java  >  How to Parse a Local JSON File from Assets Folder into a ListView?

How to Parse a Local JSON File from Assets Folder into a ListView?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 06:52:01473browse

How to Parse a Local JSON File from Assets Folder into a ListView?

Parsing a Local JSON File from Assets Folder into a ListView

To parse a local JSON file from the assets folder into a ListView, follow these steps:

  1. 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);
    }
  2. 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();
    }
  3. Display data in the ListView:

    • Create a custom adapter to bind data to the ListView.
    • Set the adapter to 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn