Search code examples
androidandroid-layoutfindviewbyid

GridLayout gridLayout = findViewById(R.id.gridLayout); crashes my app


Whenever I want to find my grid layout by ID my app crashes immediately upon starting. It is not a typo (I don't get any compiling errors).

It is the first thing I have declared in onCreate method so it doesn't crash because some other method would try to do something with the layout before the findViewById is called.

What could be the cause?

(I tried changing its ID, name... didn't work)

Part of the code:

public class MainActivity extends AppCompatActivity {

TextView countdownView, expressionView, scoreView, resultView, goView;
LinearLayout linearLayout;
GridLayout gridLayout;
CountDownTimer countDownTimer;
Random randomGenerator;
Button startGameButton;

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

    gridLayout = findViewById(R.id.gridLayout);
    //other code here}

Solution

  • I had to change casting from this:

    GridLayout gridLayout = findViewById(R.id.gridLayout);
    

    To this:

    android.support.v7.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);