Android-Droid
Android-Droid

Reputation: 14585

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", context.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?

Upvotes: 1

Views: 1292

Answers (3)

Android-Droid
Android-Droid

Reputation: 14585

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!

Upvotes: 1

jordenysp
jordenysp

Reputation: 2794

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?.

Upvotes: 0

vicla
vicla

Reputation: 11

try get context first

"context = getApplicationContext()"

Upvotes: 0

Related Questions