Alert dialog is not displaying
Asked Answered
C

5

12

Hi all I am creating an alert dialog in android by clicking a button. I used onClick property of XML and calling function. My code is

public void selectPhoneType(View view)
{
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("Select Label");
    AlertDialog alert = builder.create();
    alert.show();}

but this code is not showing alert and giving error like

BadTokenException: Unable to add window -- token null is not for an application. 

Please tell me what is wrong with this code.

Consolatory answered 26/10, 2011 at 14:1 Comment(2)
try: new AlertDialog.Builder(this)Emeric
hey thanks its work but would you please explain me what is difference between this and getAplicationContext?Consolatory
L
25
new AlertDialog.Builder(getApplicationContext());

I think this is the problem. Have you tried:

new AlertDialog.Builder(YourActivityClassName.this);
Lowbred answered 26/10, 2011 at 14:8 Comment(4)
yes i did not try this but after doing this its working. How? Please explain me.Consolatory
You were adding the context of the entire application, and not the specific Activity that you wanted to show the Dialog. There's a bit more of an explanation in the bottom of this blog post. tech.shantanugoel.com/2010/07/08/…Lowbred
No problem. Happy to be of some helpLowbred
I wish there was a other tick mark button so I can also use it. One of the best solution. :)Studley
C
1

Passing requireActivity() instead of requireContext() worked for me..!! I think it requires activity context!!.

Connoisseur answered 19/1, 2022 at 12:45 Comment(0)
B
0

If you are calling dialog code in background thread then it won't work. You should call UI related code in main thread, if you are not doing it then it will not show you the dialog.

  1. If you want show the dialog in the background task then use handler instead.

    new Handler().post(new Runnable(){ showDialog(); })

  2. Make sure create() and show() method is called.

  3. Never forgot 1st and 2nd point.

Butterworth answered 21/6, 2022 at 16:19 Comment(0)
C
0

In my case, replacing androidx.appcompat.app.AlertDialog by android.app.AlertDialog helped me:

val builder = android.app.AlertDialog.Builder(requireActivity())
Catercorner answered 13/9, 2023 at 10:4 Comment(0)
S
0

activity_main.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="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/grocery"
        android:layout_width="65dp"
        android:layout_height="72dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.089"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.024"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/chips"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="192dp"
        android:text="chips"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.167"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/fruits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:text="fruits"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.166"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/fruit_input"
        android:layout_width="166dp"
        android:layout_height="48dp"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.559"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/chips_input"
        android:layout_width="202dp"
        android:layout_height="49dp"
        android:layout_marginTop="180dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.58"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ListView
        android:id="@+id/list"
        android:layout_width="171dp"
        android:layout_height="291dp"
        android:layout_marginTop="232dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.175"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="108dp"
        android:text="submit"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.344"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt-

package com.example.practice

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import java.lang.Exception

class MainActivity : AppCompatActivity() {
    private var total=0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val fruits:TextView=findViewById(R.id.fruits)
        val chips:TextView=findViewById(R.id.chips)
        val chips_input:EditText=findViewById(R.id.chips_input)
        val fruits_input:EditText=findViewById(R.id.fruit_input)
        val grocery:ImageButton=findViewById(R.id.grocery)
        val listView:ListView=findViewById(R.id.list)
        val submit:Button=findViewById(R.id.submit)


        fruits.visibility=TextView.INVISIBLE
        chips.visibility=TextView.INVISIBLE
        fruits_input.visibility=TextView.INVISIBLE
        chips_input.visibility=TextView.INVISIBLE
        listView.visibility=TextView.INVISIBLE

           grocery.setOnClickListener {
               fruits.visibility = TextView.VISIBLE
               chips.visibility = TextView.VISIBLE
               fruits_input.visibility = TextView.VISIBLE
               chips_input.visibility = TextView.VISIBLE
               listView.visibility = TextView.VISIBLE
                try{
               var fruit_in = fruits_input.text.toString()
               var chips_in = chips_input.text.toString()

               var fruit_qty = fruit_in.toInt()
               var chips_qty = chips_in.toInt()


               var fruit_price = 100
               var chips_price = 200

               var fruits_tot = fruit_price * fruit_qty
               var chips_tot = chips_qty * chips_price

               total = fruits_tot + chips_tot

               val values = arrayOf("Fruits Total $fruits_tot", "Chips Total $chips_tot")
               val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, values)
               listView.adapter = adapter
           }
        catch(e:Exception) {

        }
           }
           submit.setOnClickListener {
               val builder=AlertDialog.Builder(this)
               builder.setTitle("Confirm")
               builder.setMessage("Total is $total")
               builder.setCancelable(false)
               builder.setPositiveButton("Yes"){_,_ ->
                   var ftotal=total.toDouble()
                   if(total>5000){
                       ftotal=total*0.9
                   }
                   val intent= Intent(this,Display::class.java).apply{
                       putExtra("total",ftotal)
                   }
                   startActivity(intent)
               }
               builder.setNegativeButton("NO"){dialog,_ ->
                   dialog.cancel()
               }
               val alertDialog=builder.create()
               alertDialog.show()
           }


    }
}

activity_display.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="match_parent"
    android:layout_height="match_parent"
    tools:context=".Display">

    <TextView
        android:id="@+id/balance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="Balance"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.254"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/value"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="10000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.595"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="320dp"
        android:text="Buy"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.411"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Display.kt-

package com.example.practice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast


class Display : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_display)
        val buy:Button=findViewById(R.id.buy)
        val value:TextView=findViewById(R.id.value)
        buy.setOnClickListener {
            try{
                val total=intent.getDoubleExtra("total",0.0)
                val bal=value.text.toString().toDouble()
                val final=bal-total
                value.text=final.toString()
                Toast.makeText(this,"Balance is $final",Toast.LENGTH_SHORT).show()
            }
            catch (e:Exception){

            }
        }
    }
}
Slinkman answered 13/3, 2024 at 15:2 Comment(1)
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?Goodman

© 2022 - 2025 — McMap. All rights reserved.