简体   繁体   中英

Changing TextView from different class

I want to update TextView from another class which is not an activity, but the app keeps crushing.. I hope you can help

This is the class where I want to update text after knowing game result

  public class GameLogic {
    ...
    public void gameResult() {
            OnePlayerGameActivity gameActivity = new OnePlayerGameActivity();
            TextView result = (TextView) gameActivity.findViewById(R.id.game_result_textView);

            getPlayerChoice();

            int computer = computerChoice();

            if (mPlayerChoice == computer) {
                mPlayerStat += 0;
                mOpponentChoice += 0;
            } else if (mPlayerChoice == 1) { //ROCK
                switch (computer) {
                    case 1: //ROCK

                        break;
                    case 2:  //PAPER
                        mOpponentStat ++;
                        result.setText("LOST");
                        break;
    ...

all code can be found on my GitHub

You are creating just a dummy instance of your activity which has no relation with the one in memory, instead pass the activity instance using

// in your OnePlayerGameActivity.java
// inside some method
GameLogic obj = new GameLogic (); // instance of GameLogic for demo
obj.gameResult(OnePlayerGameActivity.this); // pass instance

and change the methods signature as

 public void gameResult(OnePlayerGameActivity gameActivity ) {
            TextView result = (TextView) gameActivity.findViewById(R.id.game_result_textView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM