Search code examples
androidstorageinternal

Android saving data in Internal Storage NullPointerException


I have a little problem with writing a file in internal storage from my application.I'm gettin a null pointer exception,but can't find the way to fix it..and actually can't understand which one of the elements is null.

Here is the code that I'm using :

hash= jsonObj.getString("hash");
Log.w("CLIENT AUTH HASH","SHOW CLIENT AUTH HASH : "+hash);                  
FileOutputStream out = context.openFileOutput("autohash",context.MODE_PRIVATE);
out.write(hash.getBytes());
out.close();

The class where I'm trying to create and write this file is not an Activity, it's just some kind of helper class and that's why it's giving me error when I try to set context=this;. And actually the NullPointerException it thrown at this line : FileOutputStream out = context.openFileOutput("autohash",context.MODE_PRIVATE);, and I can't get it, which cause this exception :

  1. The Context

or

  1. autohash - file (exist or don't).

Second scenario :

I have the same function of saving the file in internal storage,but I'm calling that method from another activity.Here is the situation:

I have different packets received over the internet and I'm doing something like this :

BasePacket packet; //all other packets extends this class.
byte[] buffer=byte[1024];
//packet calculations
switch(packetType){
  case startPacket:
    packet = new startPacket(/*params*/);
    packet.startExecutePacket();
 case endPacket:
    //same procedure
}

and in startExecutePacket() I'm trying to save the file.

So any kind of help are welcomed!Thanks in advance!


Solution

  • CallingActivity.java

    onCreate()
    
    helperClass mHelper= new helperClass(CallingActivity.this);
    

    helperClass.java

    //declare a context
    context refContext;
    
    //constructor
    public helperClass(context mContext)
    {
       refContext=mContext;
    }
    
    //and you code
    
        hash= jsonObj.getString("hash");
        Log.w("CLIENT AUTH HASH","SHOW CLIENT AUTH HASH : "+hash);                  
        FileOutputStream out = refContext.openFileOutput("autohash",Context.MODE_PRIVATE);
        out.write(hash.getBytes());
        out.close();
    

    try with this one