0

Crash caused by use of findViewByID method

I am trying to access views from the XML layout in the java activity. I made use of the findViewByID method to do so and be able to access a TextView. Whenever I run the program it c4rashes. The logcat references the line were the findViewByID method is used but I don't seem to get the problem. package com.example.numberguessinggame; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } TextView a = findViewById(R.id.textView); Button b = findViewById(R.id.button); public void changeNum(View view){ a.setText("6 0 0"); } } <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="changeNum"

26th Aug 2019, 10:34 PM
Ibrahim Adeosun
Ibrahim Adeosun - avatar
1 Odpowiedź
0
use `findViewById` within onCreate method i.e. public class MainActivity extends AppCompatActivity { TextView a; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); a = findViewById(R.id.textView); Button b = findViewById(R.id.button); b.setOnClickListener(e -> { changeNum(); }); } public void changeNum(){ a.setText("6 0 0"); } }
1st Feb 2020, 10:12 PM
Ameer Hamza Naveed
Ameer Hamza Naveed - avatar