Android saving data in Internal Storage NullPointerException

隐身守侯 提交于 2019-12-22 18:13:57

问题


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!


回答1:


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



来源:https://stackoverflow.com/questions/7467190/android-saving-data-in-internal-storage-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!