0

我正在尝试将文本写入文件,但我似乎无法让它工作。

public static void saveState(){

        String data = age + "," ;
        FileOutputStream fos;
        Context con = getApplicationContext();
        try {
            fos = con.openFileOutput("state", 0);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e("Exception", "File write failed: " + e.toString());
        } 


    }

我环顾四周,似乎无法在没有上下文的情况下调用 openFileOutput(),但不知道“Context con = getApplicationContext()”在 Activity 之外无法正常工作。它只是告诉我该类型未定义 getapplicationcontext 。有谁可以帮我离开这里吗?

4

1 回答 1

1

您必须从调用活动传递上下文:

public static void saveState(Context context){

    String data = age + "," ;
    FileOutputStream fos;

    try {
        fos = context.openFileOutput("state", 0);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}

如何从活动中使用它:

YOUR_UTIL_CLASS.saveState(this);

以下将不起作用:

Context con = getApplicationContext();

原因:getApplicationContext()是属于的方法ContextWrapper。类Activity扩展ContextWrapper,因此可以访问此方法。方法saveState(..)可能驻留在实用程序类中。getApplicationContext()没有在那里定义。

于 2013-09-28T03:09:10.427 回答