简体   繁体   中英

Save the value of an integer in a txt file in internal storage

I am making a text game. I have a " public int x = 0 " declared at the start of my code. The value of x is controlling the users progress and main text of the story as well as the text of the radio buttons. I need to save the value of x and be able to load it in order to save the users progress using the code below. I had the saving working before by copying the code but it was just printing the value of x along with the main text of the story on load.

                /*
                Saves the game data
                 */

                String text = t.getText().toString();
                try {
                    FileOutputStream fos = openFileOutput(TEXTFILE, Context.MODE_PRIVATE);
                    fos.write(text.getBytes());
                    fos.close();
                    t.setText("");
                } catch (Exception e) {
                    e.printStackTrace();
                }


    /*
    loads the game data
     */
    try {
        FileInputStream fis = openFileInput(TEXTFILE);



        TextView t = (TextView) findViewById(R.id.mainText);


        t.setText(null);


         BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis)));

        String line;


        while ((line = reader.readLine()) != null){
            t.append(line);
            t.append("\n");
        }
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//story logic

            }else if (rb1.isChecked() && (x==2)){
                t.setText("You put the key in your pocket");
            } else if (rb2.isChecked()&& (x==2)) {
                t.setText("You took the file");

For storing something like this you'd be better using SharedPreferences

Save:

PreferenceManager.getDefaultSharedPreferences(context).edit().putInt("KEY", value);

Load:

int value = PreferenceManager.getDefaultSharedPreferences(context).getInt("KEY", defaultValue);

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