-2

I want to use a variable in another activity .

public class Score extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.score);

        TextView q1_teacherside = (TextView) findViewById(R.id.q1_score);
        TextView q2_teacherside = (TextView) findViewById(R.id.q2_score);
        TextView final_score = (TextView) findViewById(R.id.final_score);

        SharedPreferences my_preferences = PreferenceManager
            .getDefaultSharedPreferences(getApplication());

        int q1_answer = my_preferences.getInt("key1", 0);
        int q2_answer = my_preferences.getInt("key2", 0);

        if (q1_answer == 1) {
            q1_teacherside.setText("Correct");
            q1_teacherside.setTextColor(Color.GREEN);
        } else {
            q1_teacherside.setText("Incorrect");
            q1_teacherside.setTextColor(Color.RED);
        }
        if (q2_answer == 1) {
            q2_teacherside.setText("Correct");
            q2_teacherside.setTextColor(Color.GREEN);
        } else {
            q2_teacherside.setText("Incorrect");
            q2_teacherside.setTextColor(Color.RED);
        }
        int finalscore  = q1_answer + q2_answer;
        final_score.setText(finalscore + "/2");
    }
}

I want to use the variable "finalscore" in another activity .

Can anyone answer this ? Thank you .

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
kyo
  • 69
  • 2
  • 7

2 Answers2

0

Create a method in your class like

public static int getFinalScore(){
   return finalscore;
}

then in your new class

int newfinalScore = PreviousClass.getFinalScore();

or you can simply set finalscore as public.

public int finalscore;
int newfinalScore = PreviousClass.finalScore

note: don't finish the old activity so it will not return to original value.

Gangnaminmo Ako
  • 577
  • 11
  • 28
0

You can put this in this activity:

Intent i = new Intent(Score.this, NewActivity.class);
i.putExtra("finalscore",finalscore);
startActivity(i);

And then in your other activity, you can retrieve the value like this:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    int finalscore = extras.getInt("finalscore");
}

Sources:

How do I pass data between Activities in Android application?

Community
  • 1
  • 1
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97