我想在扩展FragmentStatePagerAdapter的非Activity类中将String写入文件。
任何帮助?
我希望将String写入文件文件的方法如下所示:
Context ctx;
public void saveFile() {
String xmlString = "";
for (int i=0; i<mNumOfTabs; i++) {
xmlString += days[i].toString() + "\n";
}
try{
FileOutputStream fOut = ctx.openFileOutput("config.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(xmlString);
osw.flush();
osw.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
这是logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at com.skolarac.skolarac.PageAdapter.saveFile(PageAdapter.java:78)
at com.skolarac.skolarac.Day.onActivityResult(Day.java:165)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:164)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
答案 0 :(得分:0)
问题是你的Context是null。
要解决此问题,您可以将上下文添加到类构造函数中:
public class MyClass extends FragmentStatePagerAdapter {
Context ctx;
public MyClass(Context context) { ctx = context;}
...
}