0

I'm trying to retrieve a .json file that i generated in my assets in order to test my ListView , I'm having trouble when running the app the try/catch is always returning exception and the file is never loaded,ListView returns "No data" , here's my code

Please Note that this class extends FragmentList

public View onCreateView( LayoutInflater inflater, 
        ViewGroup container,
        Bundle savedInstanceState )
    {


        View view = inflater.inflate(R.layout.frag1, container, false);
        try {
            obj =  new JSONObject(loadJSONFromAsset("Questions.json"));
            JSONArray m_jArry = obj.getJSONArray("Questions");
            ArrayList<HashMap<String, String>> formList= new ArrayList<HashMap<String, String>>();
            HashMap<String, String> m_li;

            for (int i = 0; i < m_jArry.length(); i++) 
              {
               JSONObject jo_inside = m_jArry.getJSONObject(i);

                  String Created_At = jo_inside.getString("Created At");
                  String Asker_Name = jo_inside.getString("Asker_Name");
                  String Question_Title = jo_inside.getString("QuestionTitle");
                  String Question_Body = jo_inside.getString("QuestionBody");
                  String Question_Id = jo_inside.getString("Question_Id");
                  Question question = new Question(Asker_Name, Question_Title, Question_Body, Created_At);
                  questions.add(question);

              //Add your values in your `ArrayList` as below:

             m_li=new HashMap<String, String>();
             m_li.put("Created At", Created_At );
             m_li.put("Asker_Name", Asker_Name );
             m_li.put("QuestionTitle", Question_Title);
             m_li.put("QuestionBody", Question_Body );
             m_li.put("Question_Id", Question_Id );

             formList.add(m_li);
               //Same way for other value...
              }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

here's the method loadJSONFromAsset

public String loadJSONFromAsset(String path) {
    String json = null;
    try {
    InputStream is = getActivity().getAssets().open(path);

    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;

}
SaleemKhair
  • 499
  • 3
  • 12

1 Answers1

0

I have successfully worked with json files in res/raw folder (never tried in assets). If that's an option for you, try this code:

InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
json = new String(b);
JSONObject obj = new JSONObject(json);
sebgar
  • 194
  • 3
  • 7