尝试保存缓存文件时发送广播意图时出错

时间:2013-10-01 21:57:43

标签: android android-file

我试图保存缓存文件(现在是示例文件)我的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 +输入键覆盖了所有上下文方法。

当代码到达检查位置时,app停止并且存在异常:

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)

我应该首先创建这个文件或者什么?

1 个答案:

答案 0 :(得分: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);