2013-10-01 90 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);