前提・実現したいこと
kotlinでのアプリ製作の勉強の一環で、ボタンをタップすると画面に表示されている値が
1ずつ加算されていくというものを作っています(AndroidStudio使用)。
同じクラス内に加算と表示の処理を記述するのが確実ですが、
諸事情でこれらを、クラスを分けて記述しているのですが、
クラス「MainActivity」の「counter.disp()」を実行すると、エミュレータ自体は実行はされるものの
ボタンをタップしたときにアプリが落ちます。
クラス「Data」の「disp()」まではジャンプしているようなのですが、
textView.setText("$data")の書式に問題があるように思います。
アプリが落ちた際、Logcatには
「java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference」
と表示されましたが、dispメソッド内に、単純に「textView.setText("OK")」と記述しても同様に落ちたので
変数絡みのエラーではないと思うのですが…
ソースコードにあるボタンやテキストビューのIDはAndroidStudioのデフォルトのものです。
初歩的な質問だとは思いますが、解決策をご存知の方
アドバイスをお願い致します。
該当のソースコード
kotlin
1package xxx.valuetest 2 3import android.os.Bundle 4import androidx.appcompat.app.AppCompatActivity 5import kotlinx.android.synthetic.main.activity_main.* 6 7var data = 0 8 9class MainActivity : AppCompatActivity() { 10 override fun onCreate(savedInstanceState: Bundle?) { 11 super.onCreate(savedInstanceState) 12 setContentView(R.layout.activity_main) 13 14 val counter = Data() 15 16 button.setOnClickListener{ 17 counter.disp() 18 //print() 19 } 20 } 21 22 fun print() { 23 data++ 24 textView.setText("$data") //←加算された変数が正常に表示される 25 } 26} 27 28class Data : AppCompatActivity() { 29 30 fun disp() { 31 data++ 32 //println("$data") //←Logcatに、加算された変数が出力される 33 textView.setText("$data") //←アプリが落ちる 34 textView.setText("OK") //これでも落ちる 35 } 36}
xml
1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <TextView 10 android:id="@+id/textView" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="0" 14 app:layout_constraintBottom_toBottomOf="parent" 15 app:layout_constraintLeft_toLeftOf="parent" 16 app:layout_constraintRight_toRightOf="parent" 17 app:layout_constraintTop_toTopOf="parent" /> 18 19 <Button 20 android:id="@+id/button" 21 android:layout_width="wrap_content" 22 android:layout_height="wrap_content" 23 android:layout_marginTop="340dp" 24 android:text="Button" 25 app:layout_constraintEnd_toEndOf="parent" 26 app:layout_constraintHorizontal_bias="0.517" 27 app:layout_constraintStart_toStartOf="parent" 28 app:layout_constraintTop_toTopOf="parent" /> 29 30</androidx.constraintlayout.widget.ConstraintLayout>
回答1件
あなたの回答
tips
プレビュー