.getExtras()' on a null object reference

后端 未结 2 1871
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 07:36

I am trying to pass a few values between my activities to make a game work. However, the new activity after passing the information always returns null when I try to .getExtras(

相关标签:
2条回答
  • 2021-01-26 07:48

    Move

    Bundle extras = getIntent().getExtras();
    
    ArrayList<Integer> players = extras.getIntegerArrayList("players");
    int currentPlayer = extras.getInt("newPlayerNum");
    

    into onCreate(). getIntent() needs a Context which isn't available before onCreate()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three_sign_game);
    
        // here
         Bundle extras = getIntent().getExtras();
    
         ArrayList<Integer> players = extras.getIntegerArrayList("players");
         int currentPlayer = extras.getInt("newPlayerNum");
    }
    
    0 讨论(0)
  • 2021-01-26 07:54

    Wait until onCreate to get the intent. Your trying to getIntent() when the class is instantiated instead of when the Activity is active.

    Then just assign the values found to a field and other methods inside that class can access the field.

    0 讨论(0)
提交回复
热议问题