Revoltechs
Revoltechs

Reputation: 205

Android Studio - saving user data

I want to save a file "xp.txt" to keep track of the user's experience in a game. If the file doesn't exist, I'd like to create it and write "0" in the file (to indicate 0 experience). If the file exists I'd like to read from it and save the exp to an int variable in the java class. And I'd also like to know how to change the value from "0" to some other value.

Thanks in advance!

My current code is:

        try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(XP, 0));
        out.write("0");
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        InputStream in = openFileInput(XP);
        if (in != null) {
            InputStreamReader temp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(temp);
            String str;
            StringBuilder buf = new StringBuilder();
            while ((str = reader.readLine()) != null) {
                xp = Integer.parseInt(str);
                System.out.println(xp);
            }
            in.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

But I cannot find the text file and it doesn't work as I intended.

Upvotes: 1

Views: 4697

Answers (1)

Kushal Sharma
Kushal Sharma

Reputation: 5973

You can use the following ways to store data

  1. Shared Preferences - Store private primitive data in key-value pairs.
  2. Internal Storage - Store private data on the device memory.
  3. External Storage - Store public data on the shared external storage.
  4. SQLite Databases - Store structured data in a private database.
  5. Network Connection - Store data on the web with your own network server.

I think for your use case SharedPreferences will do good. A quick example would be

To Save a value :

SharedPreferences.Editor editor = getSharedPreferences("unique_name", MODE_PRIVATE).edit();
editor.putInt("xp", 10);
editor.commit();

To Retrieve value

SharedPreferences prefs = getSharedPreferences("unique_name", MODE_PRIVATE); 
int xp = prefs.getInt("xp", 0); // will return 0 if no  value is saved

You can read more from this here.

Upvotes: 2

Related Questions