문제

im trying to save cache file (now example file) my CacheOperator class:

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

I've overrided all context methods using default alt+enter keys.

When code gets to the checked place, app stops and there is exception:

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)

Should I first create this file somewhow or what?

도움이 되었습니까?

해결책

Your context "c" is null. Seeing that you're calling this method from an activity, pass the context from your activity into your method. Note the Context parameter in the method declaration

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

Your call to the method from within your activity would be something like:

cacheOperator.saveSth(this);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top