简体   繁体   中英

Save File method in Java class or Android activity?

I've got an app that will take the user's score, save it to the current list of scores, and then display all the scores. The saveScores method is in the HighScores class, but will be called from the Activity in which the user enters their name.

Because the method is in a java class and not an Android activity, I'm having trouble getting the code to work. I've tried two options and each gives a different error:

Option 1:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.

Option 2:

FileOutputStream fileout=openFileOutput("highScores.txt", MODE_PRIVATE);
//ERROR: MODE_PRIVATE cannot be resolved to a variable

Option 1 is exactly the code from the tutorial I used, which worked when I ran it, so should be the correct option. But since there's no context in the java class, I think that's where it's having trouble. Is there any way to make this work other than moving this whole method to the activity?

For what it's worth, here's the whole saveFile method:

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

This:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);

Should be using:

FileOutputStream fileout=context.openFileOutput("highScores.txt", Context.MODE_PRIVATE);

You're getting:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.

because its looking for openFileOutput method within your HighScore class, which it will never find, because you don't have/need one, due to it being part of the Context .

Use context.openFileOutput.

But also give saveScores() a boolean return value. Return false if there is a catch. If you call it then check return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM