AlertDialog in Android Studio Kotlin not displaying - android-studio

I know I sound silly putting up this question but I simply am not able to show an AlertDialog box in my app developed using android studio and kotlin. Here is the code :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
runBlocking {
showDefaultDialog(this)
}
FuelManager.instance.basePath = getString(R.string.BaseURL)
And the function :
private fun showDefaultDialog(context: Context) {
val alertDialog = AlertDialog.Builder(context)
alertDialog.apply {
//setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _: DialogInterface?, _: Int ->
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
setNegativeButton("Negative") { _, _ ->
Toast.makeText(context, "Negative", Toast.LENGTH_SHORT).show()
}
setNeutralButton("Neutral") { _, _ ->
Toast.makeText(context, "Neutral", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
What am I missing/doing wrong? I have tried using the code without the function but that didnt work either.
(When I run the application in debug mode and set a breakpoint in the function, the breakpoint is hit, but the alertdialog doesnt show up!)
Please help.
EDIT :
I tried this (in a test app) :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showDefaultDialog(this)
Toast.makeText(this, "Hello!!!", Toast.LENGTH_SHORT).show()
}
The dialog is shown but Toast.makeText is also shown without waiting for an action on the alertDialog.
How to make the alertDialog blocking? (Is that the problem with my earlier code?)

You must never block on the main thread, so even if this did work, it would make your app freeze and crash with the dreaded Application Not Responding dialog box. Remove your Toast call in onCreate(). If you want to do something after the dialog box is closed, you have to put it inside a listener that you add to the dialog builder, such as setOnDismissListener.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showDefaultDialog(this)
}
}
private fun showDefaultDialog(context: Context) {
val alertDialog = AlertDialog.Builder(context)
alertDialog.apply {
//setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _: DialogInterface?, _: Int ->
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
setNegativeButton("Negative") { _, _ ->
Toast.makeText(context, "Negative", Toast.LENGTH_SHORT).show()
}
setNeutralButton("Neutral") { _, _ ->
Toast.makeText(context, "Neutral", Toast.LENGTH_SHORT).show()
}
setOnDismissListener {
Toast.makeText(context, "Hello!!!", Toast.LENGTH_SHORT).show()
}
}.create().show()
}
If you are going to need to do stuff with things that are private to the activity, then you can let this function take a callback:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
showDefaultDialog(this) {
// put stuff that happens after dialog closed in this lambda
Toast.makeText(this#MainActivity, "Hello!!!", Toast.LENGTH_SHORT).show()
}
}
}
inline fun showDefaultDialog(context: Context, crossinline onDismiss: ()->Unit) {
val alertDialog = AlertDialog.Builder(context)
alertDialog.apply {
//setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _: DialogInterface?, _: Int ->
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
setNegativeButton("Negative") { _, _ ->
Toast.makeText(context, "Negative", Toast.LENGTH_SHORT).show()
}
setNeutralButton("Neutral") { _, _ ->
Toast.makeText(context, "Neutral", Toast.LENGTH_SHORT).show()
}
setOnDismissListener {
onDismiss()
}
}.create().show()
}

Related

MainActivity is not showing log statements

Hi I am new to android development and the problem is Whenever I am using MainActivity in logcat as a filter it is not showing me Log statements for this Log.i(TAG, "TAG on Fb")(my tag is also MainActivity) and Log.i(TAG, "onitemclick $position") for this it is shown by its function that is onItemClick but the same happen with this statement whenever I am trying to filter it on the basis of MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userMaps = generateSampleData() as MutableList<user>
//set layout manager on the screen => RV
rvmaps.layoutManager = LinearLayoutManager(this)
//set adapter on RV
mapAdapter = mapadapter(this, userMaps, object: mapadapter.OnClickListener{
override fun onitemclick(position: Int) {
Log.i(TAG, "onitemclick $position")
val intent = Intent(this#MainActivity, googlemaps::class.java)
// here we will use putextra which help us to put extra data to another activity through data
intent.putExtra(user_data_map, userMaps[position])
startActivity(intent)
}
})
rvmaps.adapter = mapAdapter
fabcreatemap.setOnClickListener{
Log.i(TAG, "TAG on Fb")
val intent = Intent(this#MainActivity, createmap::class.java)
intent.putExtra(user_map_title, "new map name")
startActivityForResult(intent, requestcode)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(requestcode == requestCode && resultCode == Activity.RESULT_OK)
{
val usermap = data?.getSerializableExtra(user_data_map) as user
// userMaps.add(usermap)
// mapAdapter.notifyItemChanged(userMaps.size-1)
}
super.onActivityResult(requestCode, resultCode, data)
}
}

Why does navigation composable call twice?

Why does navigation composable call twice? If I set a breakpoint on the Text I will get two stops when the app runs. Thank you for your answers.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
var i: Int = 0
NavHost(navController = navController, startDestination = "s1") {
composable("s1") {
i++
Text("$i")
}
}
}
}
}

How To Show Interstitial Ads in The getView Function in Kotlin?

I'm a Beginner in Kotlin and I want a way to display Interstitial Ad every time I click on the button tvName, but on the contrary, the app crashes whenever I click on the button. I searched for the solution for a long time.
Here's MainActivity
import ...
#Suppress("UNREACHABLE_CODE")
class MainActivity : AppCompatActivity() {
lateinit var mAdView : AdView
var adapter:ChaptersAdapter?=null
var listOfChapters= ArrayList<Chapters>()
#SuppressLint("WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
loadChapters()
adapter = ChaptersAdapter(listOfChapters, this)
lvchapters.adapter = adapter
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713")
mInterstitialAd = InterstitialAd(this)
mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
}
fun loadChapters(){
listOfChapters.add(Chapters(" Chapter 1 ", applicationContext.assets.open("Chapter0.txt").bufferedReader().use {
it.readText()
}
))
listOfChapters.add(Chapters(" Chapter 2 ", applicationContext.assets.open("Chapter1.txt").bufferedReader().use {
it.readText()
}
))
}
class ChaptersAdapter: BaseAdapter {
var context:Context?=null
var listOfChaptersLocal= ArrayList<Chapters>()
constructor(listOfChapters:ArrayList<Chapters>,context:Context){
listOfChaptersLocal=listOfChapters
this.context=context
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val chapters= listOfChaptersLocal[p0]
var inflator= context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chaptersView=inflator.inflate(R.layout.list_chapters,null)
chaptersView.tvName.text= chapters.name!!
chaptersView.**tvName.setOnClickListener** {
// **i want to show the Ads in this time frame** but like this example it didn't work
if (mInterstitialAd.isLoaded) {
mInterstitialAd.show()
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.")
}
val intent =Intent(context,ChapterDetails::class.java)
intent.putExtra("name",chapters.name!!)
intent.putExtra("des",chapters.des!!)
context!!.startActivity(intent)
}
return chaptersView
}
override fun getItem(p0: Int): Any {
return listOfChaptersLocal[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return listOfChaptersLocal.size
}
}
}

problems with sending data - recyclerview

good, I'm learning kotlin
I am wanting to send the data from one recyclerview to another recyclerview. By pressing a button, the name, price and photo, I want it to be sent to the other recyclerview and then another one and thus fill the list, what is the error?
this is my code from my first recyclerview, which sends data, I am using bundle in the adapter to send it to the other recyclerview
class Adaptador_Caras(private var caras: ArrayList<Caras>,private var context: Context):RecyclerView.Adapter<Adaptador_Caras.ViewHolder>() {
class ViewHolder(var vista:View,var contexto:Context):RecyclerView.ViewHolder(vista){
fun bind(caras:Caras){
vista.ivFoto.setImageResource(caras.foto)
vista.tvNombre.text=caras.nombre
vista.tvPrecio.text=caras.precio.toString()
vista.btnIngresar.setOnClickListener {
val intent=Intent(contexto,RecyclerView::class.java)
intent.putExtra("FOTO", caras.foto)
intent.putExtra("NOMBRE",caras.nombre)
intent.putExtra("PRECIO",caras.precio)
contexto.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.lista_caras,parent,false),context)
}
override fun getItemCount(): Int {
return caras.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(caras[position])
}
}
this is the main activity, where the images are loaded
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rvCaras.layoutManager=LinearLayoutManager(this)
rvCaras.adapter=Adaptador_Caras(misCaras(),this)
}
private fun misCaras():ArrayList<Caras>{
var caras=ArrayList<Caras>()
caras.add(Caras("lucas",10,R.drawable.foto_01))
caras.add(Caras("toluca",10,R.drawable.foto_02))
caras.add(Caras("jiana",10,R.drawable.foto_03))
caras.add(Caras("joina",10,R.drawable.foto_04))
caras.add(Caras("toto",10,R.drawable.foto_05))
return caras
}
}
this is the adapter of the activity that receives the data
class AdaptadorRecibir(private var recibir:ArrayList<Recibir>,private var context:Context):RecyclerView.Adapter<AdaptadorRecibir.ViewHolder>() {
class ViewHolder(var vista: View, var contexto:Context):RecyclerView.ViewHolder(vista){
fun bind(recibir: Recibir){
vista.ivFotoR.setImageResource(recibir.fotoR)
vista.tvNombreR.text=recibir.nombreR
vista.tvPrecioR.text=recibir.precioR.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.lista_recibir,parent,false),context)
}
override fun getItemCount(): Int {
return recibir.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(recibir[position])
}
}
this is the activity receive data , here I receive the data
class RecibirRecycler : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recibir_recycler)
val parametros=this.intent.extras
if (parametros!=null){
val valor1=parametros.getInt("FOTO")
val valor2=parametros.getString("NOMBRE")
val valor3=parametros.getString("PRECIO")
tvNombreR.text=valor2
tvPrecioR.text=valor3
ivFotoR.setImageResource(valor1)
}
}
thanks for your help
Send data with bundle
Inside ViewHolder class:
vista.btnIngresar.setOnClickListener {
startActivity(
Intent(contexto, RecibirRecycler::class.java).putExtras(
bundleOf(
"FOTO" to (caras.foto?: 0),
"NOMBRE" to (caras.nombre?:""),
"PRECIO" to (caras.precio?:"))
))
}

Error "None of the following functions can be called with the arguments supplied:" with Toast

I want to create a code to click on items of RecyclerView. I found one from Internet, however it keep getting this error:
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast
Here's my code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
val users = ArrayList<User>()
val adapter = CustomAdapter(users)
recyclerView.adapter = adapter
recyclerView.addOnItemClickListener(object : OnItemClickListener {
override fun onItemClicked(position: Int, view: View) {
Toast.makeText(this, "Clicked on " + users.get(position).name, Toast.LENGTH_LONG).show()
}
})
}
interface OnItemClickListener {
fun onItemClicked(position: Int, view: View)
}
fun RecyclerView.addOnItemClickListener(onClickListener: OnItemClickListener) {
this.addOnChildAttachStateChangeListener(object : RecyclerView.OnChildAttachStateChangeListener {
override fun onChildViewDetachedFromWindow(view: View) {
view.setOnClickListener(null)
}
override fun onChildViewAttachedToWindow(view: View) {
view.setOnClickListener {
val holder = getChildViewHolder(view)
onClickListener.onItemClicked(holder.adapterPosition, view)
}
}
})
}
How can I fix that error message?
Toast.makeText(this#YOUR_ACTIVITY_NAME, "Clicked on " + users.get(position).name, Toast.LENGTH_LONG).show()
//In Activity use:
Toast.makeText(this#YOUR_ACTIVITY_NAME, "your message", Toast.LENGTH_LONG).show()
//In Fragments use:
Toast.makeText(requireActivity(), "your message", Toast.LENGTH_LONG).show()
Your problem will be solved...

Resources