Home > Software engineering >  I'm using Android Studio. When I add button in activity_main The app stop on the AVD
I'm using Android Studio. When I add button in activity_main The app stop on the AVD

Time:06-29

When I add button in "activity_main" The app stop on the AVD but If I delete the button, app run normally.

If I make the button as comment or delete this, The app run correctly. What should I do?

please teach me What I have to do.

This is Logcat.

2022-06-29 21:41:45.282 10486-10486/com.JS.noteapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.JS.noteapp, PID: 10486
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.JS.noteapp/com.JS.noteapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.view.Window.getLayoutInflater()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.view.Window.getLayoutInflater()' on a null object reference
        at android.app.Activity.getLayoutInflater(Activity.java:5060)
        at com.JS.noteapp.MainActivity.<init>(MainActivity.kt:13)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

And This is my activity_main. I think it hasn't problem.......

<?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/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Memo List"
        android:textSize="28sp"
        android:textStyle="bold"
        android:textColor="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@ id/edittest_memo"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:hint="App Memo..."
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="22dp"
        android:layout_marginBottom="12dp"/>

    <Button
        android:id="@ id/button_add"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:text="Add"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:background="@drawable/button_red"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/edittest_memo" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@ id/edittest_memo"
        app:layout_constraintTop_toBottomOf="@ id/title"
        tools:layout_editor_absoluteX="0dp"
        android:layout_margin="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

And This is my MainActivity.kt

package com.JS.noteapp

import android.annotation.SuppressLint
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.JS.noteapp.databinding.ActivityMainBinding

@SuppressLint("StaticFieldLeak")
class MainActivity : AppCompatActivity() {

    var binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)   // create ActivityMainBinding Object.
    lateinit var db: MemoDatabase   // lateinit 나중에 초기화.
    var memoList = listOf<MemoEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)    // change as comment.

        setContentView(binding.root)    // get root layout of activity_main.xml

        binding.buttonAdd.setOnClickListener {
            val memo = MemoEntity(null, binding.edittestMemo.text.toString())
            insertMemo(memo)
        }

        binding.recyclerView.layoutManager = LinearLayoutManager(this)

        db = MemoDatabase.getInstance(this)!!
    }

    //1. Insert Data
    //2. Get Data
    //3. Delete Data
    //4. Set recyclerView

    fun insertMemo(memo: MemoEntity) {
        // 1, MainThread vs WorkerThread(Background Thread)
        // UI관련 작업 - MainThread 에서 이루어짐
        // 데이터 통신 - WorkerThread 에서 이루어짐

        object : AsyncTask<Unit, Unit, Unit>() {
            override fun doInBackground(vararg params: Unit?) {
                db.memoDAO().insert(memo)
            }

            override fun onPostExecute(result: Unit?) { // execute 후에 작업할 내용
                super.onPostExecute(result)
                getAllMemos()
            }
        }
    }

    fun getAllMemos() {
        val getTask = object : AsyncTask<Unit, Unit, Unit>() {
            override fun doInBackground(vararg params: Unit?) {
                memoList = db.memoDAO().getAll()
            }

            override fun onPostExecute(result: Unit?) {
                super.onPostExecute(result)
                setRecyclerView(memoList)
            }
        }

        getTask.execute()
    }

    fun deleteMemo() {

    }

    fun setRecyclerView(memoList: List<MemoEntity>) {
        binding.recyclerView.adapter = MyAdapter(this, memoList)
    }
}

CodePudding user response:

You are using .inflate() in a null object in the first line of your MainActivity code.
See Binding docs here.

To initialize binding you should do like this:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater) // initialized here
        setContentView(binding.root) // set the view to root binding

        // now you can call your binding for anything
    }
}

CodePudding user response:

@Thales Isidoro

I change my project like this.

  1. MainActivity

package com.JS.noteapp

import android.annotation.SuppressLint
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.JS.noteapp.databinding.ActivityMainBinding

@SuppressLint("StaticFieldLeak")
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding   // create ActivityMainBinding Object.
    lateinit var db: MemoDatabase   // lateinit 나중에 초기화.
    var memoList = listOf<MemoEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)    // change as comment.

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)    // get root layout of activity_main.xml

        binding.buttonAdd.setOnClickListener {
            val memo = MemoEntity(null, binding.edittestMemo.text.toString())
            insertMemo(memo)
        }

        binding.recyclerView.layoutManager = LinearLayoutManager(this)

        db = MemoDatabase.getInstance(this)!!
    }

    //1. Insert Data
    //2. Get Data
    //3. Delete Data
    //4. Set recyclerView

    fun insertMemo(memo: MemoEntity) {
        // 1, MainThread vs WorkerThread(Background Thread)
        // UI관련 작업 - MainThread 에서 이루어짐
        // 데이터 통신 - WorkerThread 에서 이루어짐

        object : AsyncTask<Unit, Unit, Unit>() {
            override fun doInBackground(vararg params: Unit?) {
                db.memoDAO().insert(memo)
            }

            override fun onPostExecute(result: Unit?) { // execute 후에 작업할 내용
                super.onPostExecute(result)
                getAllMemos()
            }
        }
    }

    fun getAllMemos() {
        val getTask = object : AsyncTask<Unit, Unit, Unit>() {
            override fun doInBackground(vararg params: Unit?) {
                memoList = db.memoDAO().getAll()
            }

            override fun onPostExecute(result: Unit?) {
                super.onPostExecute(result)
                setRecyclerView(memoList)
            }
        }

        getTask.execute()
    }

    fun deleteMemo() {

    }

    fun setRecyclerView(memoList: List<MemoEntity>) {
        binding.recyclerView.adapter = MyAdapter(this, memoList)
    }
}

  1. activity_main

<?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/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Memo List"
        android:textSize="28sp"
        android:textStyle="bold"
        android:textColor="@color/black"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@ id/edittest_memo"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:hint="App Memo..."
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginStart="22dp"
        android:layout_marginBottom="12dp"/>

    <Button
        android:id="@ id/button_add"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="12dp"
        android:text="Add"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:background="@drawable/button_red"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/edittest_memo" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@ id/edittest_memo"
        app:layout_constraintTop_toBottomOf="@ id/title"
        tools:layout_editor_absoluteX="0dp"
        android:layout_margin="20dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

but I still have Error Logcat

2022-06-29 22:07:31.140 11738-11738/com.JS.noteapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.JS.noteapp, PID: 11738
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.JS.noteapp/com.JS.noteapp.MainActivity}: android.view.InflateException: Binary XML file line #33 in com.JS.noteapp:layout/activity_main: Binary XML file line #33 in com.JS.noteapp:layout/activity_main: Error inflating class Button
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: android.view.InflateException: Binary XML file line #33 in com.JS.noteapp:layout/activity_main: Binary XML file line #33 in com.JS.noteapp:layout/activity_main: Error inflating class Button
     Caused by: android.view.InflateException: Binary XML file line #33 in com.JS.noteapp:layout/activity_main: Error inflating class Button
     Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:241)
        at com.google.android.material.internal.ThemeEnforcement.checkAppCompatTheme(ThemeEnforcement.java:211)
        at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:146)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:75)
        at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:228)
        at com.google.android.material.button.MaterialButton.<init>(MaterialButton.java:219)
        at com.google.android.material.theme.MaterialComponentsViewInflater.createButton(MaterialComponentsViewInflater.java:43)
        at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:129)
        at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1565)
        at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1616)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1059)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at com.JS.noteapp.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:60)
        at com.JS.noteapp.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:54)
        at com.JS.noteapp.MainActivity.onCreate(MainActivity.kt:21)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2022-06-29 22:07:31.141 11738-11738/com.JS.noteapp E/AndroidRuntime:     at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

  • Related