2

I'm a beginner to Android Studio and I'm just learning how to read in JSON files. I used logcat to find out that I'm getting an exception on the line declaraing the JSONArray dataList. My code is below for reference.

try{
            JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
            JSONArray dataList = jsonObject.getJSONArray("eateries");
            //Log.d("test", String.valueOf(dataList.length()));
            for(int i = 0; i < dataList.length(); i++){
                String EateryName = dataList.getJSONObject(i).getString("name");
                EateryList.add(EateryName);
            }
        }catch (JSONException e){
            e.printStackTrace();
            //Log.d("test", "exception");
        }
Dinesh
  • 1,410
  • 2
  • 16
  • 29
Jerry Wang
  • 23
  • 3

2 Answers2

0

Follow these steps to solve your issue.

  1. Check for asset folder/dir via code (file path must be accurate with .json).
  2. Check for file created/present in dir using File object (if not then create file).
  3. Check for file size by reading the file using FileInputStream.
  4. If size > 0 then get data in byte-Array and convert byte-Array to string.
  5. Now, you have a string of json data. Create JsonArray(your_string) and perform further operations you like.
    Every step has a code available on this stack overflow. Find and solve.
    Hope it helps.
Viraj S
  • 390
  • 2
  • 12
0

Check GrIsHu answer simply you have to do is create assests folder in root of project

enter image description here

Here is the original Link

String myJsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "your.json");
Log.i("My data", jsonFileString);

Gson gson = new Gson();
Type listUserType = new TypeToken<List<User>>() { }.getType();

List<User> users_ = gson.fromJson(myJsonFileString, listUserType);
for (int i = 0; i < users.size(); i++) {
  Log.i("data", "> Item " + i + "\n" + users.get(i));
}

go through original post

Chanaka Weerasinghe
  • 5,404
  • 2
  • 26
  • 39