0

I am writing a simple app in which at one point you initialize instances of my custom class "Player" and then pass these objects on to the next activity via parcelable. This was working fine so far, however I completely redid the code for the button (I used a different approach before). Now, I get an error if I dont declare the Player instances final. When I hover over "player 1" in for example this line:

bundle.putParcelable("EXTRA_PLAYER_1", player1);

It says "Variable 'player 1' is accessed from within inner class, needs to be declared final". This is the relevant part of the "onCreate" method:

etPlayer4 = (EditText) findViewById(R.id.etPlayer4);
String namePlayer4 = etPlayer4.getText().toString();
Player player4 = new Player();
player4.setPlayerName(namePlayer4);
player4.setPlayerScore(0);

btnStartGame = (Button) findViewById(R.id.btnStartGame);
btnStartGame.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent=new Intent(CreatePlayersScreen.this,ScoreScreen.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("EXTRA_PLAYER_1", player1);
        bundle.putParcelable("EXTRA_PLAYER_2", player2);
        bundle.putParcelable("EXTRA_PLAYER_3", player3);
        bundle.putParcelable("EXTRA_PLAYER_4", player4);
        intent.putExtras(bundle);
        startActivity(intent);
    }
});

How can I avoid declaring the Player instances final? Thank you!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Kubi
  • 73
  • 6

1 Answers1

0

Define your player objects outside of the onCreate so you can use them in anywhere in the class. You can still assign them values in your oncreate

// define
Player player4 , player3,
        player2, player1;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    etPlayer4 = (EditText) findViewById(R.id.etPlayer4);
    String namePlayer4 = etPlayer4.getText().toString();

    // assign
    player4 = new Player();
    player4.setPlayerName(namePlayer4);
    player4.setPlayerScore(0);

    btnStartGame = (Button) findViewById(R.id.btnStartGame);
    btnStartGame.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(CreatePlayersScreen.this,ScoreScreen.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable("EXTRA_PLAYER_1", player1);
            bundle.putParcelable("EXTRA_PLAYER_2", player2);
            bundle.putParcelable("EXTRA_PLAYER_3", player3);
            bundle.putParcelable("EXTRA_PLAYER_4", player4);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    });
}
petey
  • 16,914
  • 6
  • 65
  • 97