我有一个应用程序,它将获取用户的分数,将其保存到当前分数列表,然后显示所有分数。 saveScores 方法位于 HighScores 类中,但将从用户输入姓名的 Activity 中调用。
因为该方法位于 java 类中,而不是 Android Activity 中,所以我无法让代码正常工作。我尝试了两个选项,每个选项都会给出不同的错误:
选项 1:
FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.
选项 2:
FileOutputStream fileout=openFileOutput("highScores.txt", MODE_PRIVATE);
//ERROR: MODE_PRIVATE cannot be resolved to a variable
选项 1 正是 tutorial 中的代码我使用过,运行时有效,所以应该是正确的选择。但由于 java 类中没有上下文,我认为这就是它遇到麻烦的地方。 除了将整个方法移至 Activity 中之外,还有什么方法可以使这项工作正常进行吗?
就其值(value)而言,这是整个 saveFile 方法:
public void saveScores(Context context, ArrayList<Score> scores){
// save to file
try{
String allScores ="";
FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE); // The line in question.
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
for (int i=0; i<scores.size(); i++)
allScores += ((i+1)+". "+scores.get(i).toString()+"\n");
outputWriter.write(allScores);
outputWriter.close();
}catch(FileNotFoundException e){
System.out.println("SaveScores ERROR: File Not Found.");
}catch(IOException e){
System.out.println("SaveScores ERROR: See Stack Trace below.");
e.printStackTrace();
}
最佳答案
这个:
FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
应该使用:
FileOutputStream fileout=context.openFileOutput("highScores.txt", Context.MODE_PRIVATE);
您将得到:
FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.
因为它正在寻找openFileOutput
你的 HighScore 类中的方法,它永远不会找到,因为你没有/不需要一个方法,因为它是 Context
的一部分。
关于java - Java 类或 Android Activity 中的 Save File 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384225/