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
  • 1
  • 12

3 Answers3

0

try this code:

BufferedReader reader = null;
try {
reader = new BufferedReader(
    new InputStreamReader(getAssets().open("jsonfile1.json")));

// do reading, usually loop until end of file reading  
String mLine;
while ((mLine = reader.readLine()) != null) {
   //process line
   ...
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
     try {
         reader.close();
     } catch (IOException e) {
         //log the exception
     }
 }
 }

make sure your file path is exist or not

Damini Mehra
  • 3,214
  • 3
  • 12
  • 24
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,651
  • 1
  • 14
  • 17
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,440
  • 4
  • 29
  • 37