0

I want to read/parse a JSON file in Android Studio.

The JSON file, that is contained in the assets folder is this one:

{
   "Person":
   {
   "Name": "John"
   }
}

The class that is supposed to read the file is this one:

import ...

public class ParseJ
{
    private Context context;
    String name;


    public String RetName() throws JSONException {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONObject student = obj.getJSONObject("Person");
        name = student.getString("Name");
        return name;
    }

    public String loadJSONFromAsset()
    {
        String json = null;
        try
        {
            InputStream is = context.getAssets().open("Test.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;
        }
        return json;
    }
}

Then it gets called in MainActivity like this:

String firstname = new String();
ParseJ parsetest = new ParseJ();
TextView onomaTView;


 try {
        firstname = parsetest.RetName();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    //textview
    onomaTView = (TextView) findViewById(R.id.onoma);

        onomaTView.setText("ONOMA:" + firstname);
    }                                  
```

When i build and run the app it crashes immediately and looking at the Logcat it says the following message: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference

Which lets me to believe it cannot read the file and it just returns null.

Henry
  • 42,982
  • 7
  • 68
  • 84
Perlio34
  • 3
  • 2
  • https://stackoverflow.com/questions/9544737/read-file-from-assets – xIsra Nov 22 '20 at 08:13
  • Does this answer your question? [read file from assets](https://stackoverflow.com/questions/9544737/read-file-from-assets) – xIsra Nov 22 '20 at 08:14
  • try this https://stackoverflow.com/questions/19945411/how-can-i-parse-a-local-json-file-from-assets-folder-into-a-listview – aziz k'h Nov 22 '20 at 11:06

1 Answers1

0

You are getting null pointer because Context is null now create a contructor and pass context in it like this

 public class ParseJ
    {
        private Context context;
        String name;
    
    public ParseJ(Context context){
    this.context = context
    }

then in Mainactivity while creating object of ParseJ

ParseJ parsetest = new ParseJ(this);
Wahdat Jan
  • 3,988
  • 3
  • 21
  • 46