0

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");
Jobin
  • 5,610
  • 5
  • 38
  • 53
KingBuzzo
  • 29
  • 7

1 Answers1

1

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

hibob
  • 746
  • 7
  • 17
  • can you explain more? im a noob. when i put this code in it didnt work. The value im using is called x and is declared at the start of the code. Also, i need to know how to save the value of a TextView which in my code is called t. – KingBuzzo Dec 15 '16 at 22:44
  • also i need to save the value of a radiobutton text which is called rb1 and also the visibility of the text. – KingBuzzo Dec 15 '16 at 22:55