我在openFileOutput上遇到此错误(FILENAME,Context.MODE_PRIVATE);
之前我使用过此代码,我不知道为什么它现在不能正常工作。错误读取:方法openFileOutput(String,int)未定义类型SaveProjects
package com.example.musicvideomaker;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import com.example.musicvideomaker.Projects;
public class SaveProjects {
FileOutputStream fos;
public ArrayList<Projects> Projects;
public void saveProject(Projects project, String FILENAME)
{
this.Projects.add(project);
try
{
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
由于您不在活动中,因此您需要使用上下文来调用&#34; openFileOutput&#34;。虽然您的Context要么需要在Application文件中静态声明,要么从Activity调用SaveProject类,您可以将上下文作为类的参数传递(尽管这是不好的做法)。然后你可以试试这个:
public class SaveProjects {
private Context context;
FileOutputStream fos;
public ArrayList<Projects> Projects;
public SaveProjects(Context context) {
this.context = context;
}
public void saveProject(Projects project, String FILENAME)
{
this.Projects.add(project);
try
{
fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}