0

I'm making a game that requires some statistics to be saved to memory (games played, games won, etc). I've tried to use sharedpreferences but there seems to be poor documentation from what I can see, and I haven't been able to get it to work. Am I missing something?

try {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        SharedPreferences stats = getPreferences(MODE_PRIVATE);
        CharSequence gampjla = "Games played: " + stats;
        Toast toast = Toast.makeText(context, gampjla, duration);
        toast.show();

        gamesPlayed++;
        SharedPreferences.Editor editor = stats.edit();
        editor.putInt("gameplay", gamesPlayed).commit();
        CharSequence gampla = "Games played: " + gamesPlayed;
        Toast toayst = Toast.makeText(context, gampla, duration);
        toayst.show();

    }
    catch (Exception e) {
            Context context = getApplicationContext();
            CharSequence errormsg = "Unable to save!! " + e;
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, errormsg, duration);
            toast.show();
    }

I've tried variations but nothing works! Thanks for any help!

EDIT: The random letters in some of the variable names is because I wanted a different variable name for testing and because I was getting frustrated so I couldn't be bothered at that point!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ollie R
  • 31
  • 1
  • 6
  • 1
    'commit()' returns a boolean status so you may want to check that for more info - also why are you relying on 'toString()' to get gameplay stats rather than stats.getInt("gameplay")? Post what you're getting for the first toast. –  Apr 09 '18 at 16:45
  • The post I used at first, also on StackOverflow, wanted so save variables as well and the accepted answer used getString. (The code is a lot different and I think it uses an earlier version) [One I used](https://stackoverflow.com/questions/11688689/save-variables-after-quitting-application?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – Ollie R Apr 09 '18 at 17:05
  • Just to be clear - you are using the implied 'toString()' of the SharedPreferences implementation to get data which is not part of the interface so it's most likely just Object toString - use a proper 'getX' like getInt since you 'putInt'. –  Apr 09 '18 at 17:08
  • Oh, I hadn't even noticed that! I'll give it a try! – Ollie R Apr 09 '18 at 17:11

2 Answers2

0

Change this:

CharSequence gampjla = "Games played: " + stats;

to:

CharSequence gampjla = "Games played: " + stats.getInt("gameplay",-1);
0

Solved! It was a dumb issue. I had written 'putInt' but used 'getString'.

Ollie R
  • 31
  • 1
  • 6