Question

I am trying to access a 'score' integer variable from a main.class and display the score within the textview on a second screen. So far I have this code:

//main.java
Intent myIntent = new Intent(this, Screen2.class);
     myIntent.putExtra("scores", score);
     startActivity(myIntent);

//screen2.java

TextView tView= (TextView)findViewById(R.id.textView);

public void getScore(){
Bundle bundle=getIntent().getExtras();
int value=bundle.getInt("scores");
}

How can I get the score to appear within the textfield?

Was it helpful?

Solution

Use below code that returns value from bundle

public int getScore(){
   Bundle bundle = getIntent().getExtras();
   return bundle.getInt("scores");
}

and set to textview like:

TextView tView = (TextView)findViewById(R.id.textView);
tView.setText(String.valueOf(getScore()));

Cause You used void as return type so when you call this methood you didnt get value and the value is in local variable that not accessible out side method. and using String.valueOf(getScore()) you properly convert int to string

OTHER TIPS

just put this line after getting score from intent.

tView.setText(String.valueOf(value));  //value is your score that you get from intent

I would say you dont even have to pass the variable to other activity by using static variable. A static variable is a variable which is present in the memory till the program is executing.

Here is the way:-

//MainActivity
public static int score;
@override
oncreate()
{

    score=32;
    Intent intent=new Intent(this,secondActivity.class);
    startActivity(intent);
}


//Secondactivity

 @override
 oncreate()
 {
      TextView tv=(TextView)findViewById(R.id.score_txt);
      tv.setText("Score : "+MainActivity.score);
 }

Hope it helps you...

thx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top