3

I'm trying to learn SharedPreferences, but I'm getting an error.

My layout has one button that reeacts to the method doThis

This is my java:

package com.example.sharedprefs;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    int i = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void doThis (View view){
        i++;
        SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = sharedPref.edit();
        prefEditor.putInt("userChoice",i);
        prefEditor.commit();
        int number = sharedPref.getInt("userChoice", 0);
        Toast.makeText(getApplicationContext(), number, Toast.LENGTH_LONG).show();
    }

}

Only thing I can pinpoint in logcat is 10-15 19:28:17.707: E/AndroidRuntime(16657): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1

EGHDK
  • 17,818
  • 45
  • 129
  • 204

3 Answers3

8

Your toast is incorrect. You are passing a number into the toast hoping that it will give a string, instead is thinks it should be looking up a string resource value. Try:

Toast.makeText(getContext(), number + "" , Toast.LENGTH_LONG).show();

Edit, other than that, your code is fine.

ahodder
  • 11,353
  • 14
  • 71
  • 114
  • Perfect. Thanks can anyone comment on the correctness of my actual `SharedPref` code? Is it written correctly. – EGHDK Oct 15 '12 at 23:44
  • @EGHDK, Yes, in essence it is correct. I would, however, place it [the commiting] in its own method. – ahodder Oct 16 '12 at 14:35
0

You can't make a integer type to Toast message.

you can only put String type to the message parameter to Toast.makeText method.

as for solution, you can try these

Toast.makeText(getApplicationContext(), Integer.toString(number), Toast.LENGTH_LONG).show();

Toast.makeText(getApplicationContext(), ""+number, Toast.LENGTH_LONG).show();

and yes, your sharedpreference usage is perfectly fine.

Dan Lee
  • 126
  • 1
  • 4
0

The problem here is you are using an integer value as the Toast string. You have to do the following.

String.valueOf(number);

or

Integer.toString(number);

Your sharedpreferences part is ok. But for more info about SharedPreferences you can visit this post. Android SharedPreferences Example

Kashfa Khan
  • 2,165
  • 1
  • 11
  • 8