Home > Java > javaTutorial > body text

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

Barbara Streisand
Release: 2024-11-08 06:52:01
Original
542 people have browsed it

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);
    }
    Copy after login
  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();
    }
    Copy after login
  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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template