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」は null です。アクティビティからこのメソッドを呼び出していることを確認したら、コンテキストをアクティビティからメソッドに渡します。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 に答える