Android write file to Internal Storage issue
I have a little issue with writing a file in Internal Storage in Android. I'm trying to do it from a helper class which is not an activity. Here is the code I'm using :
FileOutputStream fos = context.openFileOutput("media", cont开发者_如何转开发ext.MODE_PRIVATE);
fos.write(media.getBytes());
fos.close();
And it throws me a null pointer exception at the first line. I tried with this.context.openFileOutput("media",this.context.MODE_PRIVATE);
& this.context.openFileOutput("media",Context.MODE_PRIVATE);
but nothing helps.
Any idea how to solve that issue?
Actually I had the same issue and here is the solution :
You can use this :
Activity1.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();
Hope this helps!
try get context first
"context = getApplicationContext()"
Verifies that the activity from which the instance of the class helper pass the reference of context, you specify a little more the scenary, for example, who inherits the helper class or how do you set the instance of the context attribute?.
精彩评论