[java] How can I parse a local JSON file from assets folder into a ListView?

I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the ListView)

This is my main layout

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:measureWithLargestChild="false"
    android:orientation="vertical"
    tools:context=".CatList" >


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/titlebar" >

        <TextView
            android:id="@+id/Title1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/app_name"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#ff1c00"
            android:textIsSelectable="false" />

    </RelativeLayout>

    <ListView
        android:id="@+id/listFormulas"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

    </ListView>

</LinearLayout>

And this is my main activity

package com.wildsushii.quickphysics;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.ListView;

public class CatList extends Activity {



    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);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cat_list);
        ListView categoriesL = (ListView)findViewById(R.id.listFormulas);

        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        Context context = null;
        try {
            String jsonLocation = AssetJSONFile("formules.json", context);
            JSONObject formArray = (new JSONObject()).getJSONObject("formules");
            String formule = formArray.getString("formule");
            String url = formArray.getString("url");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //My problem is here!!
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.cat_list, menu);
        return true;
    }
}

I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON

    {
    "formules": [
    {
      "formule": "Linear Motion",
      "url": "qp1"
    },
    {
      "formule": "Constant Acceleration Motion",
      "url": "qp2"
    },
    {
      "formule": "Projectile Motion",
      "url": "qp3"
    },
    {
      "formule": "Force",
      "url": "qp4"
    },
    {
      "formule": "Work, Power, Energy",
      "url": "qp5"
    },
    {
      "formule": "Rotary Motion",
      "url": "qp6"
    },
    {
      "formule": "Harmonic Motion",
      "url": "qp7"
    },
    {
      "formule": "Gravity",
      "url": "qp8"
    },
    {
      "formule": "Lateral and Longitudinal Waves",
      "url": "qp9"
    },
    {
      "formule": "Sound Waves",
      "url": "qp10"
    },
    {
      "formule": "Electrostatics",
      "url": "qp11"
    },
    {
      "formule": "Direct Current",
      "url": "qp12"
    },
    {
      "formule": "Magnetic Field",
      "url": "qp13"
    },
    {
      "formule": "Alternating Current",
      "url": "qp14"
    },
    {
      "formule": "Thermodynamics",
      "url": "qp15"
    },
    {
      "formule": "Hydrogen Atom",
      "url": "qp16"
    },
    {
      "formule": "Optics",
      "url": "qp17"
    },
    {
      "formule": "Modern Physics",
      "url": "qp18"
    },
    {
      "formule": "Hydrostatics",
      "url": "qp19"
    },
    {
      "formule": "Astronomy",
      "url": "qp20"
    }
  ]
}

I have tried a lot of things and even delete the entire project to make a new one :(

This question is related to java android json android-listview local

The answer is


Just summarising @libing's answer with a sample that worked for me.

enter image description here

val gson = Gson()
val todoItem: TodoItem = gson.fromJson(this.assets.readAssetsFile("versus.json"), TodoItem::class.java)

private fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Without this extension function the same can be achieved by using BufferedReader and InputStreamReader this way:

val i: InputStream = this.assets.open("versus.json")
val br = BufferedReader(InputStreamReader(i))
val todoItem: TodoItem = gson.fromJson(br, TodoItem::class.java)

With Kotlin have this extension function to read the file return as string.

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Parse the output string using any JSON parser.


{ // json object node
    "formules": [ // json array formules
    { // json object 
      "formule": "Linear Motion", // string
      "url": "qp1"
    }

What you are doing

  Context context = null; // context is null 
    try {
        String jsonLocation = AssetJSONFile("formules.json", context);

So change to

   try {
        String jsonLocation = AssetJSONFile("formules.json", CatList.this);

To parse

I believe you get the string from the assests folder.

try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
        e.printStackTrace();
} catch (JSONException e) {
        e.printStackTrace();
}

If you are using Kotlin in android then you can create Extension function.
Extension Functions are defined outside of any class - yet they reference the class name and can use this. In our case we use applicationContext.
So in Utility class you can define all extension functions.


Utility.kt

fun Context.loadJSONFromAssets(fileName: String): String {
    return applicationContext.assets.open(fileName).bufferedReader().use { reader ->
        reader.readText()
    }
}

MainActivity.kt

You can define private function for load JSON data from assert like this:

 lateinit var facilityModelList: ArrayList<FacilityModel>
 private fun bindJSONDataInFacilityList() {
    facilityModelList = ArrayList<FacilityModel>()
    val facilityJsonArray = JSONArray(loadJSONFromAsserts("NDoH_facility_list.json")) // Extension Function call here
    for (i in 0 until facilityJsonArray.length()){
        val facilityModel = FacilityModel()
        val facilityJSONObject = facilityJsonArray.getJSONObject(i)
        facilityModel.Facility = facilityJSONObject.getString("Facility")
        facilityModel.District = facilityJSONObject.getString("District")
        facilityModel.Province = facilityJSONObject.getString("Province")
        facilityModel.Subdistrict = facilityJSONObject.getString("Facility")
        facilityModel.code = facilityJSONObject.getInt("code")
        facilityModel.gps_latitude = facilityJSONObject.getDouble("gps_latitude")
        facilityModel.gps_longitude = facilityJSONObject.getDouble("gps_longitude")

        facilityModelList.add(facilityModel)
    }
}

You have to pass facilityModelList in your ListView


FacilityModel.kt

class FacilityModel: Serializable {
    var District: String = ""
    var Facility: String = ""
    var Province: String = ""
    var Subdistrict: String = ""
    var code: Int = 0
    var gps_latitude: Double= 0.0
    var gps_longitude: Double= 0.0
}

In my case JSON response start with JSONArray

[
  {
    "code": 875933,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Amabele Clinic",
    "gps_latitude": -32.6634,
    "gps_longitude": 27.5239
  },

  {
    "code": 455242,
    "Province": "Eastern Cape",
    "District": "Amathole DM",
    "Subdistrict": "Amahlathi LM",
    "Facility": "Burnshill Clinic",
    "gps_latitude": -32.7686,
    "gps_longitude": 27.055
  }
]

Source code How to fetch Local Json from Assets folder

https://drive.google.com/open?id=1NG1amTVWPNViim_caBr8eeB4zczTDK2p

    {
        "responseCode": "200",
        "responseMessage": "Recode Fetch Successfully!",
        "responseTime": "10:22",
        "employeesList": [
            {
                "empId": "1",
                "empName": "Keshav",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "9654267338",
                "empDesignation": "Sr. Java Developer",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "2",
                "empName": "Ram",
                "empFatherName": "Mr Dasrath ji",
                "empSalary": "9999999999",
                "empDesignation": "Sr. Java Developer",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "3",
                "empName": "Manisha",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "8826420999",
                "empDesignation": "BusinessMan",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "4",
                "empName": "Happy",
                "empFatherName": "Mr Ramesh Chand Gera",
                "empSalary": "9582401701",
                "empDesignation": "Two Wheeler",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            },
            {
                "empId": "5",
                "empName": "Ritu",
                "empFatherName": "Mr Keshav Gera",
                "empSalary": "8888888888",
                "empDesignation": "Sararat Vibhag",
                "leaveBalance": "3",
                "pfBalance": "60,000",
                "pfAccountNo.": "12345678"
            }
        ]
    }


 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee);


        emp_recycler_view = (RecyclerView) findViewById(R.id.emp_recycler_view);

        emp_recycler_view.setLayoutManager(new LinearLayoutManager(EmployeeActivity.this, 
        LinearLayoutManager.VERTICAL, false));
        emp_recycler_view.setItemAnimator(new DefaultItemAnimator());

        employeeAdapter = new EmployeeAdapter(EmployeeActivity.this , employeeModelArrayList);

        emp_recycler_view.setAdapter(employeeAdapter);

        getJsonFileFromLocally();
    }



    public String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = EmployeeActivity.this.getAssets().open("employees.json");       //TODO Json File  name from assets folder
            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;
        }
        return json;
    }

    private void getJsonFileFromLocally() {
        try {

            JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
            String responseCode = jsonObject.getString("responseCode");
            String responseMessage = jsonObject.getString("responseMessage");
            String responseTime = jsonObject.getString("responseTime");

            Log.e("keshav", "responseCode -->" + responseCode);
            Log.e("keshav", "responseMessage -->" + responseMessage);
            Log.e("keshav", "responseTime -->" + responseTime);


            if(responseCode.equals("200")){

            }else{
                Toast.makeText(this, "No Receord Found ", Toast.LENGTH_SHORT).show();
            }

            JSONArray jsonArray = jsonObject.getJSONArray("employeesList");                  //TODO pass array object name
            Log.e("keshav", "m_jArry -->" + jsonArray.length());


            for (int i = 0; i < jsonArray.length(); i++)
            {
                EmployeeModel employeeModel = new EmployeeModel();

                JSONObject jsonObjectEmployee = jsonArray.getJSONObject(i);


                String empId = jsonObjectEmployee.getString("empId");
                String empName = jsonObjectEmployee.getString("empName");
                String empDesignation = jsonObjectEmployee.getString("empDesignation");
                String empSalary = jsonObjectEmployee.getString("empSalary");
                String empFatherName = jsonObjectEmployee.getString("empFatherName");

                employeeModel.setEmpId(""+empId);
                employeeModel.setEmpName(""+empName);
                employeeModel.setEmpDesignation(""+empDesignation);
                employeeModel.setEmpSalary(""+empSalary);
                employeeModel.setEmpFatherNamer(""+empFatherName);

                employeeModelArrayList.add(employeeModel);

            }       // for

            if(employeeModelArrayList!=null) {
                employeeAdapter.dataChanged(employeeModelArrayList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

Using OKIO

public static String readJsonFromAssets(Context context, String filePath) {
    
        try {
            InputStream input = context.getAssets().open(filePath);
            BufferedSource source = Okio.buffer(Okio.source(input));
            return source.readByteString().string(Charset.forName("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
}

and then...

String data = readJsonFromAssets(context, "json/some.json"); //here is my file inside the folder assets/json/some.json

Type reviewType = new TypeToken<List<Object>>() {}.getType();

if (data != null) {
    Object object = new Gson().fromJson(data, reviewType);
}

Method to read JSON file from Assets folder and return as a string object.

public static String getAssetJsonData(Context context) {
            String json = null;
            try {
                InputStream is = context.getAssets().open("myJson.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;
            }

            Log.e("data", json);
            return json;

        }

Now for parsing data in your activity:-

String data = getAssetJsonData(getApplicationContext());
        Type type = new TypeToken<Your Data model>() {
        }.getType();
  <Your Data model> modelObject = new Gson().fromJson(data, type);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to android-listview

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference CardView not showing Shadow in Android L android - listview get item view by position Custom Listview Adapter with filter Android How to create a custom navigation drawer in android Swipe ListView item From right to left show delete button How can I parse a local JSON file from assets folder into a ListView? Add Items to ListView - Android ListView with Add and Delete Buttons in each Row in android Converting JSONarray to ArrayList

Examples related to local

Load local images in React.js Access to Image from origin 'null' has been blocked by CORS policy How can I parse a local JSON file from assets folder into a ListView? How to make a local variable (inside a function) global How to securely save username/password (local)? Is it possible to run .php files on my local computer? How to keep the local file or the remote file during merge using Git and the command line? Mocking methods of local scope objects with Mockito Load HTML file into WebView PHP server on local machine?