Search code examples
androidkotlinpopupbottomnavigationview

Popup Dialog Box doesn't work, app crashes


I wanted to do a small popup Window (Dialog Box) with TextInputLayout, TextView and button. The thing is I have multiple fragments, with a bottomNavigationMenu. On top of bottomNavigationMenu i have a FloatingButton that i want to be responsible for DialogBox, but my app just crash without any error on emulator. Do i need to add the code to all of my fragments (or only one where i want the button to be avalible), or there is something wrong with my code.

this is a screenshot of my app with bottomNavigationMenu, the button in the middle have id "fab"

If there is more files required to solve this problem let me know i will add this file.

MainActivity.kt

class MainActivity : AppCompatActivity() {

private val home = HomeFragment()
private val player = PlayerFragment()
private val profile = ProfileFragment()
private val settings = SettingsFragment()

private val popupButton: Button = findViewById(R.id.fab)


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val bottomNav: BottomNavigationView = findViewById(R.id.bottomNavigationView)
    bottomNav.background = null
    bottomNav.menu.findItem(R.id.placeholder).isEnabled = false
    replaceFragment(home)
    bottomNav.setOnItemSelectedListener {
        when (it.itemId) {
            R.id.home -> replaceFragment(home)
            R.id.player -> replaceFragment(player)
            R.id.profile -> replaceFragment(profile)
            R.id.settings -> replaceFragment(settings)
        }
        true
    }
        popupButton.setOnClickListener {
            showDialog()
        }
}

private fun replaceFragment(fragment: Fragment) {
    val transaction = supportFragmentManager.beginTransaction()
    transaction.replace(R.id.fragment_container, fragment)
    transaction.commit()
}
private fun showDialog(){
    val dialog = Dialog(this)
    dialog.setContentView(R.layout.popup)
    dialog.show()
  }
}

popup.xml

<?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="350dp"
android:layout_height="350dp"
android:layout_gravity="center"
android:background="@drawable/cercle_backgoud">

<ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@drawable/samoyed_popup"
    app:layout_constraintBottom_toTopOf="@+id/textView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:contentDescription="@string/samoyed"
    />

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fontFamily="@font/roboto_light_italic"
    android:gravity="center"
    android:text="@string/enter_youtube_video_link"
    android:textColor="@color/white"
    android:textSize="20sp"
    app:layout_constraintBottom_toTopOf="@+id/textInputLayout" />

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:gravity="center"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.53"
    app:placeholderText="https://www.youtube.com/watch? 
    v=HHezQOZ_2xk&amp;ab_channel=BoyWithUke"
    app:placeholderTextColor="@color/grey_card" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/roboto_light_italic"
    android:text="@string/add"
    android:textColor="@color/white"
    android:textStyle="bold"
    android:outlineSpotShadowColor="@color/teal_200"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textInputLayout" />


</androidx.constraintlayout.widget.ConstraintLayout>

logs

02/17 20:10:13: Launching 'app' on Pixel 4 API 31.
Install successfully finished in 86 ms.
$ adb shell am start -n "eu.tuto.youtubeproject/eu.tuto.youtubeproject.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: eu.tuto.youtubeproject
Connected to process 20790 on device 'Pixel_4_API_31 [emulator-5554]'.
Connecting to eu.tuto.youtubeproject
Connected to the target VM, address: 'localhost:56510', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/.youtubeprojec: Late-enabling -Xcheck:jni
W/.youtubeprojec: Unexpected CPU variant for X86 using defaults: x86_64
W/re-initialized>: type=1400 audit(0.0:87): avc: granted { execute } for path="/data/data/eu.tuto.youtubeproject/code_cache/startup_agents/fafda4ce-agent.so" dev="dm-5" ino=147913 scontext=u:r:untrusted_app:s0:c147,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c147,c256,c512,c768 tclass=file app=eu.tuto.youtubeproject
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-2ca9b3e0.jar
W/.youtubeprojec: DexFile /data/data/eu.tuto.youtubeproject/code_cache/.studio/instruments-2ca9b3e0.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/.youtubeprojec: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/.youtubeprojec: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10147; state: ENABLED
W/ActivityThread: Application eu.tuto.youtubeproject is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
W/System: A resource failed to call close. 
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1431)
V/GraphicsEnvironment: ANGLE Developer option for 'eu.tuto.youtubeproject' set to: 'default'
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
W/.youtubeprojec: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/.youtubeprojec: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: eu.tuto.youtubeproject, PID: 20790
    java.lang.RuntimeException: Unable to start activity ComponentInfo{eu.tuto.youtubeproject/eu.tuto.youtubeproject.MainActivity}: java.lang.ClassCastException: com.google.android.material.floatingactionbutton.FloatingActionButton cannot be cast to android.widget.Button
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        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:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
    Caused by: java.lang.ClassCastException: com.google.android.material.floatingactionbutton.FloatingActionButton cannot be cast to android.widget.Button
        at eu.tuto.youtubeproject.MainActivity.onCreate(MainActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:8051)
        at android.app.Activity.performCreate(Activity.java:8031)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
        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:2210) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loopOnce(Looper.java:201) 
        at android.os.Looper.loop(Looper.java:288) 
        at android.app.ActivityThread.main(ActivityThread.java:7839) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
I/Process: Sending signal. PID: 20790 SIG: 9
Disconnected from the target VM, address: 'localhost:56510', transport: 'socket'

Solution

  • Could you move below code to under setContentView

    private val popupButton: Button = findViewById(R.id.fab)
    

    Like below

    setContentView(R.layout.activity_main)
    val popupButton: Button = findViewById(R.id.fab)
    

    Also you have to change

    val popupButton: Button = findViewById(R.id.fab)
    

    To

    val popupButton: FloatingActionButton = findViewById(R.id.fab)