我想要make机制,我可以从app中的任何地方调用来写入文件。
我下一堂课:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import android.content.Context;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
import android.content.Context;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class LogFile extends Activity {
public void writeFile(String msg)
{
Log.d("writeFile", "writeToFile");
try {
Context context = getApplicationContext();
FileOutputStream fos = context.openFileOutput("log.txt", Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
BufferedWriter outputStream = new BufferedWriter(osw);
outputStream.write(msg);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("writeFile", "File not found");
} catch (NullPointerException e) {
e.printStackTrace();
Log.d("writeFile", "NullPointerException");
} catch (IOException e) {
e.printStackTrace();
Log.d("writeFile", "File problems");
}
}
}
但是在这一行
Context context = getApplicationContext();
我有错误
W/System.err: java.lang.NullPointerException
W/System.err: at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:185)
W/System.err: at com.example.tracklogger.LogFile.writeFile(LogFile.java:37)
答案 0 :(得分:0)
我不确定这是"对"解决问题或使其发挥作用的方法。 我认为问题在于你传递了Activity的上下文的值(并且这是null,因为它抛出了Exception)并且你需要Application的上下文。
在我个人的案例中,我解决了类似的问题如下:
GlobalVars.java文件,包含所有"全局变量",类似于Applications上下文(不是Activity的上下文):
public class GlobalVars extends Application {
public static Context context;
@Override public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
}
从这里采取:Getting the Application Context
祝你好运,编码愉快!