0

我试图保存缓存文件(现在是示例文件)我的 CacheOperator 类:

public class CacheOperator {

Context c;

public void saveSth() {
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = null;
    try {
            fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(string.getBytes());
            fos.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
}

我已经使用默认的 alt+enter 键覆盖了所有上下文方法。

当代码到达检查位置时,应用程序停止并出现异常:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.app.partyme/pl.app.partyme.MainActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2085)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2110)
    at android.app.ActivityThread.access$600(ActivityThread.java:138)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4940)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at pl.app.partyme.tools.CacheOperator.saveSth(CacheOperator.java:49)
    at pl.app.partyme.MainActivity.onCreate(MainActivity.java:29)
    at android.app.Activity.performCreate(Activity.java:5255)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)

我应该先以某种方式创建这个文件还是什么?

4

1 回答 1

0

您的上下文“c”为空。看到您正在从活动中调用此方法,请将活动中的上下文传递到您的方法中。注意Context方法声明中的参数

public void saveSth(Context c) {
    String FILENAME = "hello_file";
    String string = "hello world!";

    FileOutputStream fos = null;
    try {
            fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(string.getBytes());
            fos.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
}

您在活动中对该方法的调用将类似于:

cacheOperator.saveSth(this);
于 2013-10-01T22:23:05.110 回答