相关文章推荐
紧张的绿豆  ·  IOException: ...·  1 年前    · 
寂寞的日光灯  ·  Spring MVC ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Very nice to join the community! For my first post, I have a problem to use getAssets() from a class except main. In my MainActivity Class, it works well, but if I want to use getAssets() by LoadJSONFromAsset() in my other Class, it doesn't. I read that I need to use a context, and I tried to.

What is the problem in my code? How do I have to use Context in the MainActivity?

The report is:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference

Thanks for your advice.

MainActivity Class:

public class MainActivity  extends Activity  {
TextToSpeech TTS;
static Context myContext;
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Json mydata=new Json();
    mydata.LireStation(14);
    Button BadB=(Button)findViewById(R.id.Bad);
    Button BagB=(Button)findViewById(R.id.Bag);

My Json Class:

public class Json extends Activity {
JSONArray myJsonArray;
public Json(){
    System.out.println("Json !!!!");
    try {
        System.out.println("on est dans le try !!!");
        String myJsonString=loadJSONFromAsset();
        myJsonArray = new JSONArray(myJsonString);
        //On fabrique un joli tableau pour ranger chacune des points GPS
        int arrSize = myJsonArray.length();
        System.out.println("longueur  :  "+arrSize);
        List<Double> lat = new ArrayList<Double>(arrSize);
        List<Double> lon = new ArrayList<Double>(arrSize);
        for (int i = 0; i < arrSize; ++i)
            //System.out.println("on est dans le for !!!");
            JSONObject STATION=myJsonArray.getJSONObject(i);
            JSONObject objetField=STATION.getJSONObject("fields"); //on refabrique un objet json fils du pere Alelouia
            lat.add((Double) (objetField.getDouble("stop_lat")));
            lon.add((Double) (objetField.getDouble("stop_lon")));
            //Double res = obj.getDouble("departement");
            //System.out.println(lat);
        //JSONObject STATION=myJsonArray.getJSONObject(2);
        //LireStation(10);  //  go à l'affichage
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("ECHEC DE LECTURE JSON");
public  String LireStation(int index)
    String infos="";
    try {
        String myJsonString;
        myJsonString=loadJSONFromAsset();
        JSONArray myJsonArray = new JSONArray(myJsonString);
        JSONObject STATION=myJsonArray.getJSONObject(index);
        JSONObject objetFielddd = STATION.getJSONObject("fields");
        String NomStation;String NomArret; String CodePostal;
        NomStation = (objetFielddd.getString("stop_name"));
        NomArret=(Double.toString(objetFielddd.getDouble("stop_lat")));
        CodePostal=(objetFielddd.getString("code_postal"));
        infos="Station"+" "+NomStation+" "+"adresse"+NomArret+"kodpostal"+CodePostal;
    catch (Exception e) {
        e.printStackTrace();
        infos="Pas de données";
    return infos;
public String loadJSONFromAsset()  {
    String json = null;
    try {
        AssetManager mngr = MainActivity.myContext.getAssets();
        InputStream is = mngr.open("positionStations.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;

You are using the reference of MainActivity in the code directly in the line

 AssetManager mngr = MainActivity.myContext.getAssets();

But instead you should use the context of the class from where you are trying to get Assetmanager. So it should be like

AssetManager assetMgr = this.getAssets(); //this means reference to current activity 

I found this solution and it works very well. First put a static context in MainActivity and call the context in the Json Class:

MainActivity:

public class MainActivity  extends Activity  {
TextToSpeech TTS;
static Context myContext;
boolean found=false; //valeur sattion trouvee ou non
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myContext = this;

Json Class:

    public  String loadJSONFromAsset()  {
    String json = null;
    try {
        InputStream is = MainActivity.myContext.getAssets().open("positionStations.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;
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.