Android将文件写入内部存储问题
我对在Android的内部存储中编写文件有点问题。我试图从一个不是活动的helper类中完成它。以下是我正在使用的代码:Android将文件写入内部存储问题,android,file,Android,File,我对在Android的内部存储中编写文件有点问题。我试图从一个不是活动的helper类中完成它。以下是我正在使用的代码: FileOutputStream fos = context.openFileOutput("media", context.MODE_PRIVATE); fos.write(media.getBytes()); fos.close(); 它在第一行抛出一个空指针异常。我尝试了this.context.openFileOutput(“media”,this.context.
FileOutputStream fos = context.openFileOutput("media", context.MODE_PRIVATE);
fos.write(media.getBytes());
fos.close();
它在第一行抛出一个空指针异常。我尝试了this.context.openFileOutput(“media”,this.context.MODE\u PRIVATE)代码>&this.context.openFileOutput(“media”,context.MODE_PRIVATE)代码>但没有任何帮助
知道如何解决这个问题吗?首先尝试获取上下文
“context=getApplicationContext()”首先尝试获取上下文
“context=getApplicationContext()”验证类帮助程序实例从中传递context引用的活动,例如,您可以指定多一点场景,谁继承了helper类,或者如何设置context属性的实例?验证类helper实例从中传递context引用的活动,您可以指定多一点场景,例如,谁继承了helper类,或者如何设置上下文属性的实例?事实上,我也遇到了同样的问题,下面是解决方案:
您可以使用以下选项:
活动1.java
onCreate()
helperClass mHelper= new helperClass(CallingActivity.this);
//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();
helperClass.java
onCreate()
helperClass mHelper= new helperClass(CallingActivity.this);
//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();
希望这有帮助 实际上我也遇到了同样的问题,下面是解决方案:
您可以使用以下选项:
活动1.java
onCreate()
helperClass mHelper= new helperClass(CallingActivity.this);
//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();
helperClass.java
onCreate()
helperClass mHelper= new helperClass(CallingActivity.this);
//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();
希望这有帮助 实际上,我在扩展自定义类的类中尝试这样做;因为它向我显示了一个错误…我认为上下文正在返回null。实际上,我正在扩展自定义类的类中尝试这样做。我不能使用context context=this;因为它向我显示了一个错误…我认为上下文正在返回null。