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.