1

how am i going to pass an integer value from the textview to the next activity? currently im using string as my sharedpreferences and everytime im changing it to int my app force close.

here's my code on mainactivity

int scoreText=50;
public static final String PREFS_COIN= "MyPreferenceFile";

protected void onCreate(Bundle savedInstanceState) {

    public void checkAnswer()
    {   String answer=answerText.getText().toString();  

        if(isCorrect(answer))
        {       

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("What are you a GENIUS?!");
            builder.setMessage("Nice one, Genius! You have P10!");
            builder.setIcon(android.R.drawable.btn_star);
            builder.setPositiveButton("View Trivia",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                scoreText+=10;
                scoreNew=scoreText;
                scoreTxt.setText(""+ scoreNew);
                SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
                SharedPreferences.Editor editor2=settings2.edit();
                editor2.putString("coins", scoreTxt.getText().toString());
                editor2.commit();
                Intent intent=new Intent(getApplicationContext(), Luzon1Trivia.class);
                startActivity(intent);
                overridePendingTransition(R.animator.transition_fade_in, R.animator.transition_fade_out);
                //startActivity(new Intent(Luzon1.this, Luzon2.class));

                ;} });
            AlertDialog alert = builder.create();
            alert.show(); // Show Alert Dialog
             scoreTxt.setVisibility(View.GONE);

            //disable all the buttons and textview
            answerText.setEnabled(false);
            answerButton.setClickable(false);       
                        }
  }

everytime the user guessed the correct answer, a +10 coin will be given. the problem is, in the second activity i cannot add/subtract the sharedpreference value since its declared as string. what happens is "60 +10" appears in the textview

here's my code in activity 2

public static final String PREFS_COIN= "MyPreferenceFile";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.luzon2);

        scoreTxt = (TextView)findViewById(R.id.score);
        SharedPreferences settings2=getSharedPreferences(PREFS_COIN, 0);
        scoreTxt.setText(settings2.getString("coins", ""));
Fahim
  • 11,496
  • 4
  • 36
  • 56
Pucckat19
  • 37
  • 1
  • 6

3 Answers3

2

You shouldn't use Shared Preferences to pass information between activities, Shared Preferences is inteded to be used to store persistent information when the Application is destroyed.

To pass information between activities you should use an Intent (the same Intent that is used to start the "destiny" activity)

Intent newActivityIntent = new Intent(originActivity.this, destinyActivity.class);
newActivityIntent.putExtra(KEY_STRING, integerValue);
this.startActivity(newActivityIntent);//Assuming you're starting an activity from another one

Edit: This has been also answered here and here. I would recommend you to search before posting a question.

Community
  • 1
  • 1
Sherekan
  • 536
  • 3
  • 14
  • Of proposals so far, this one shows the most awareness of how Android is intended to work. – Chris Stratton Mar 16 '15 at 16:42
  • but if i dont use sharedpreferences, the coin gained by the user will be reset. am i right? – Pucckat19 Mar 16 '15 at 16:47
  • what i want to happen is store the coin gained by the user, and then pass the coin across activities. – Pucckat19 Mar 16 '15 at 16:48
  • That is precisely what Intent extras are intended to do. On the other hand, if you want to user to generate a coin and still have it around tomorrow, or next week, then use a shared preference. – Chris Stratton Mar 16 '15 at 16:50
  • The value in the first activity will be erased only if the activity is destroyed, but activity destruction is not the same as application destruction, you need to store that value in a Bundle in "onSaveInstanceState(Bundle outState)" method (documentation here: http://developer.android.com/training/basics/activity-lifecycle/recreating.html). You may need this behaviour if, for example, you let your user go back to the original activity (which could have been destroyed to free memory) and need the original coin value. – Sherekan Mar 16 '15 at 16:51
  • I would recommend you to read through Android Activity Lifecycle and understand how everything works, as Activities are one of the first things you have to dominate when developing for Android. (http://developer.android.com/reference/android/app/Activity.html) – Sherekan Mar 16 '15 at 16:53
  • @Sherekan thank you so much. – Pucckat19 Mar 16 '15 at 16:56
0

Just use a static variable to hold this. It's much easier to implement since all you have to do is call it instead of passing it around to other intents like a mad man.

  public static int coins;  

To call it use your class instance name:

  MyClass.coins; 

So to add:

MyClass.coins+=10;
scoreTxt.setText(Integer.toString(MyClass.coins));

MyClass is your class. If your class is called MainActivity then it will be that (MainActivity).

.coins is the variable inside that class, your just making a reference to that variable.

The nice thing about static is using it as a learning tool. It's a great way to explore instances and references.

Or you can add all of this to every activity, and don't forget about handling device rotations:

Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("coins","value");
startActivity(i);

To retrieve those values:

Bundle extras = getIntent().getExtras();
if (extras != null) {
     coins = Integer.parseInt(extras.getString("coins"));
}

To set:

    coins+=10;
    scoreTxt.setText(coins);

Device rotation: Passing Extras and screen rotation

Community
  • 1
  • 1
Petro
  • 2,741
  • 3
  • 20
  • 46
  • This is not such a great answer in the context of Android, where you can have what appears to be continuing flow to the user, but where the subsequent part may happen or resume in a new process where this has never been initialized. – Chris Stratton Mar 16 '15 at 16:41
  • where should i put MyClass.coins; – Pucckat19 Mar 16 '15 at 16:43
  • @Pucckat19 - don't. This is not good solution for your problem. It can have a role in some advanced uses, but getting it to work reliably is going to add unnecessary complexity unjustified by your simple needs. Pass an Intent Extra as Sherekan proposes. – Chris Stratton Mar 16 '15 at 16:44
  • Just initialize this "MyClass.coins" inside of your parent activity (MainActivity) or whataver your name might be. @ChrisStratton there is nothing wrong with static variables: http://stackoverflow.com/questions/2475978/using-static-variables-in-android – Petro Mar 16 '15 at 16:46
  • @Petro - no, and this is precisely what is wrong with this approach. You are assuming that the parent activity will have run in the current process, which is an utterly unsafe assumption on Android, where android can without warning kill the process that held that activity and run the subsequent activity in a different process. Static variables do have legitimate uses on Android, but only by those who understand the complications they introduce! – Chris Stratton Mar 16 '15 at 16:48
  • I understand your concerns. However, intent.putExtra can be a nightmare for passing a simple int/string around. It adds a ridiculous amount of code for something so simple (just think about screen orientation changes). Using ROM manager with a Galaxy device, the static variable lives after a "clean". As long as we structure the static variables in the parent class. – Petro Mar 16 '15 at 16:57
  • No. A static variable's lifetime cannot outlast its containing process, unless you *add additional code* to persist it somewhere else. Whatever test you *thought* was checking for this obviously did not involve trying to access the value in a process different than the one in which it was set. Intent extras are intended precisely to make passing around simple values easy. – Chris Stratton Mar 16 '15 at 17:13
0

You have to parse the string and get a float/integer value.

int myNewInt = Integer.parseInt("theString");

in your case you have to do :

int myNewInt = Integer.parseInt(settings2.getString("coins", ""));

And I think you need to set the default value as 0 in your

settings2.getString("coins", "0")
user1305336
  • 141
  • 1
  • 1
  • 11
  • Yes, something like this would be needed to make the current mechanism work, though the current mechanism is not the best way to solve the ultimate problem. – Chris Stratton Mar 16 '15 at 16:43
  • my app has stopped :( – Pucckat19 Mar 16 '15 at 16:45
  • @Pucckat19 - that is an utterly useless problem report. No one can help you unless you identify the actual error message. – Chris Stratton Mar 16 '15 at 16:46
  • im sorry. but everytime i use Integer.parseInt my app keeps force close. – Pucckat19 Mar 16 '15 at 16:51
  • If you want to develop on Android, you must learn how to use the logcat tool to learn *why* your app has force closed. Until you do that, you will not be able to ask questions that result in real debugging help. – Chris Stratton Mar 16 '15 at 16:52