1

The following is the code I am using to read a JSON file stored in assets folder.

public class ReadJson extends Activity {
public String loadJSONFromAsset() {
    String json1 = null;
    try {

        InputStream is = getAssets().open("jsonfile1.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json1 = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json1;
} 
}

The app crashes and shows

"Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference" exception.

How to resolve this?

aditya
  • 165
  • 2
  • 12

2 Answers2

0

You may try something like below.

try{
    StringBuilder buf=new StringBuilder();
    InputStream json = getAssets().open("jsonfile1.json");
    BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));
    String str;

    while ((str=in.readLine()) != null) {
      buf.append(str);
    }

    in.close();
} catch(Exception e){

}

Make sure your jsonfile1.json is a file of assets folder.

Md Sufi Khan
  • 1,751
  • 1
  • 14
  • 19
0

When are you calling loadJSONFromAsset()? It seems like you are calling it before the Activity is created. Try the following:

public class ReadJson extends Activity {

    @Override
    protected void onCreate(Bundle savedInstaceState) {
        super.onCreate(savedInstaceState);
        loadJSONFromAsset(); // call after super.onCreate()!!!!
        /// ...
    }

}
Eduard B.
  • 6,735
  • 4
  • 27
  • 38