Search code examples
androidandroid-intenttextviewandroid-activityonresume

Update a TextView on resuming main activity


Friends in this code provided below, i want to refresh my text view upon resume from play intent. But whenever i try to define my textview out of OnCreate but inside my main class (after static int score), my app crashes.

public class MainProjectActivity extends Activity {
    /** Called when the activity is first created. */

    static int Score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Display Scores
        final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
        displayScores.setText("Your Score : "+ Score);

        //Play Game button activity
        Button gameButton = (Button)findViewById(R.id.PlayButton);
        gameButton.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
                startActivity(play);
            }
        });

Solution

  • try this:

    public class MainProjectActivity extends Activity {
        /** Called when the activity is first created. */
    TextView displayScores;
        static int Score = 0;
    @Override
    protected void onResume(){
        super.onResume();
        // code to update the date here
        displayScores.setText("Your Score : "+ Score);
    
    }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            //Display Scores
            displayScores = (TextView)findViewById(R.id.scoreDisplay);
            displayScores.setText("Your Score : "+ Score);
    
            //Play Game button activity
            Button gameButton = (Button)findViewById(R.id.PlayButton);
            gameButton.setOnClickListener(new OnClickListener() {
    
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
                    startActivity(play);
                }
            });