Reputation: 51
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}
Upvotes: 2
Views: 2172
Reputation: 397
replace your line by this
androidx.gridlayout.widget.GridLayout gridLayout = findViewById(R.id.gridLayout);
Upvotes: 4
Reputation: 1
findViewbyId
is changed in android studio 3.*
refer
findViewById()
signature change
All instances of the findViewById()
method now return <T extends View> T
instead of View
. This change has the following implications:
This may result in existing code now having ambiguous return type, for example if there is both someMethod(View)
and someMethod(TextView)
that takes the result of a call to findViewById()
.
When using Java 8 source language, this requires an explicit cast to View when the return type is unconstrained (for example, assertNotNull(findViewById(...)).someViewMethod())
.
Overrides of non-final findViewById()
methods (for example, Activity.findViewById())
will need their return type updated.
EditText message=super.findViewById(R.id.txtmessage);
I am a new android learner. Directly trying codes of videos in my learning
Upvotes: 0
Reputation: 51
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);
Upvotes: 2
Reputation: 99
Change it
from
gridLayout = findViewById(R.id.gridLayout);
to
gridLayout = (GridLayout) findViewById(R.id.gridLayout);
You should cast the result from findViewById
function
Upvotes: -3
Reputation: 195
Either cast it like A.El Saeed mentioned in his answer
gridLayout = (GridLayout)findViewById(R.id.gridLayout);
or post your XML code also because sometime, it may possible that there will be some typo in your XML code or maybe you are using different grid layout id
than defined in the XML
Upvotes: -2