0

I'm trying to make a quiz app where you click the plus button to add a quiz. A button pops up on the screen and you can click that to either play or edit the quiz. When I click the newly created button once its fine but the second time I click it, the app crashes. Does anyone have any idea how I can fix this error specifically?

Main Activity page:

    package com.example.k_ari

import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        showEditTextDialogue()
    }

    private fun showEditTextDialogue() {
        val btn = findViewById<FloatingActionButton>(R.id.btn)
        btn.setOnClickListener{

            val inflator = layoutInflater
            val layout = findViewById<LinearLayout>(R.id.mainlayout)
            val dialogLayout = inflator.inflate(R.layout.edit_text_layout, null)
            val editText = dialogLayout.findViewById<EditText>(R.id.et_editText)
            val builder = AlertDialog.Builder(this)
            val newbutton = Button(this@MainActivity)
            val btnintent = Intent(this, Newbtn::class.java)
            val dialogLayout2 = inflator.inflate(R.layout.new_button_option, null)

            newbutton.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            newbutton.width=1010
            newbutton.height=300
            newbutton.gravity = Gravity.CENTER
            newbutton.translationX= 65F
            newbutton.setTextColor(Color.parseColor("#FFFFFFFF"))
            newbutton.setBackgroundColor(Color.parseColor("#250A43"))

            with(builder) {
                setTitle("Title:")
                setPositiveButton("Ok"){dialog, which ->
                    layout.addView(newbutton)
                    newbutton.text = editText.text.toString()
                }
                setNegativeButton("Cancel"){dialog, which ->
                    Log.d("Main", "Negative button clicked")
                }
                setView(dialogLayout)
                show()
            }
            newbutton.setOnClickListener{
                with(builder){
                    setPositiveButton("Play"){dialog, which ->
                        startActivity(btnintent)
                    }
                    setPositiveButton("Edit"){dialog, which ->
                        startActivity(btnintent)
                    }
                    setView(dialogLayout2)
                    show()
            }
        }
    }
}}

Xml file:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="56dp"
        android:backgroundTint="#250A43"
        android:backgroundTintMode="add"
        android:clickable="true"
        android:contentDescription="@string/todo"
        android:tint="#250A43"
        android:translationX="280dp"
        android:translationY="580dp"
        app:backgroundTint="#250A43"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.56"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:rippleColor="#FFFFFF"
        app:srcCompat="@android:drawable/ic_input_add"
        android:focusable="true" />
    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:id="@+id/mainlayout"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>

</LinearLayout>

Logcat:

2020-12-28 13:48:47.521 26648-26648/com.example.k_ari E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.k_ari, PID: 26648 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. at android.view.ViewGroup.addViewInner(ViewGroup.java:5458) at android.view.ViewGroup.addView(ViewGroup.java:5277) at android.view.ViewGroup.addView(ViewGroup.java:5249) at androidx.appcompat.app.AlertController.setupCustomContent(AlertController.java:657) at androidx.appcompat.app.AlertController.setupView(AlertController.java:475) at androidx.appcompat.app.AlertController.installContent(AlertController.java:233) at androidx.appcompat.app.AlertDialog.onCreate(AlertDialog.java:279) at android.app.Dialog.dispatchOnCreate(Dialog.java:708) at android.app.Dialog.show(Dialog.java:422) at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1009) at com.example.k_ari.MainActivity$showEditTextDialogue$1$2.onClick(MainActivity.kt:66) at android.view.View.performClick(View.java:8178) at android.widget.TextView.performClick(TextView.java:16104) at android.view.View.performClickInternal(View.java:8147) at android.view.View.access$3700(View.java:888) at android.view.View$PerformClick.run(View.java:30233) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:246) at android.app.ActivityThread.main(ActivityThread.java:8414) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:596) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

  • Problem is this part -> layout.addView(newbutton). You are trying to add same view multiple times. Maybe this will help you -> https://stackoverflow.com/questions/8937380/how-to-set-id-of-dynamic-created-layout/35551268 – Haris Dec 28 '20 at 18:59
  • Can you specify what you mean? How am I adding the same view multiple times? I'm trying to add a new button on only one layout. I also tried the link you gave but I still can't get around this. – CinnamonToastCrunch12 Dec 28 '20 at 19:37

1 Answers1

1

The reason you are experiencing this crash is because your new button uses the same view twice here:

 newbutton.setOnClickListener{
            with(builder){
                setPositiveButton("Play"){dialog, which ->
                    startActivity(btnintent)
                }
                setPositiveButton("Edit"){dialog, which ->
                    startActivity(btnintent)
                }
                setView(dialogLayout2)
                show()
        }

Here dialogLayout2 is inflated when your add button is clicked and immediately you add a click listener to your newly created button. Initially dialogLayout2 doesn't have a parent until the first click on the new button, when you do a second click dialogLayout2 already has a parent, so therefore it crashes. The possible solution would be to inflate your alert dialog layout in the new button click listener like here:

newbutton.setOnClickListener{
            val dialogLayout2 = inflator.inflate(R.layout.new_button_option, null)
            with(builder){
                setPositiveButton("Play"){dialog, which ->
                    startActivity(btnintent)
                }
                setPositiveButton("Edit"){dialog, which ->
                    startActivity(btnintent)
                }
                setView(dialogLayout2)
                show()
        }
    }
MPetrychko
  • 351
  • 1
  • 9