2013-10-01 51 views
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(); 
     } 
} 

我overrided使用默认替代所有上下文方法+回车键。

当代码获取到托运的地方,应用程序停止,有例外:

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) 

我应该先创建这个文件somewhow还是什么?

+0

我没有看到上下文℃;初始化/分配到任何地方 – dymmeh

+0

@dymmeh你能帮我吗? – pawel

+0

添加了一个应该帮助的答案。 – dymmeh

回答

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);