function not running when called code mostly copyed from video - android-studio

I'm trying to request Bluetooth permissions, however it is skipping the function that asks for the permission, and just shows the text saying Bluetooth Permission Denied.
the code:
class MainActivity : AppCompatActivity() {
lateinit var perms_button: Button
private val BLUETOOTH_PERM_CODE = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
perms_button = findViewById(R.id.perms_button)
perms_button.setOnClickListener {
checkPermission(Manifest.permission.BLUETOOTH, BLUETOOTH_PERM_CODE)//this is supposed to run the function that requests permissions
}
}
private fun checkPermission(permission: String, requestCode: Int) {// this is the function that doesn't run
if (ContextCompat.checkSelfPermission(this#MainActivity, permission) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this#MainActivity, arrayOf(permission), requestCode)
} else {
Toast.makeText(this#MainActivity, "Permission Granted already", Toast.LENGTH_LONG).show()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == BLUETOOTH_PERM_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
perms_button.setText("Permission Granted")
Toast.makeText(this#MainActivity, "Bluetooth Permission Granted", Toast.LENGTH_SHORT).show()
}else {
Toast.makeText(this#MainActivity, "Bluetooth Permission Denied", Toast.LENGTH_SHORT).show()
}
}
}
}
link to the video I got the code from: https://youtu.be/_2fo2Z6O5D4
I'm unsure if the problem has to do with the changes I had to make for my app(It always the changes you made)
thanks in advance for any help.

Related

My Interstitial Ad not working, does not start

My interstitial ad is not working, Logcat only shows "The interstitial ad wasn't ready yet." I followed AdMob instructions but it doesn't start. As an additional note currently my app shows banner ads, no error appears.
This is my code:
class MainActivity : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
private final var TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
adView?.loadAd(adRequest)
if (mInterstitialAd != null) {
InterstitialAd.load(this, AD_UNIT_ID, adRequest, object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError.toString())
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d(TAG, "Ad was loaded")
mInterstitialAd = interstitialAd
}
})
mInterstitialAd?.fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.")
}
override fun onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
Log.d(TAG, "Ad dismissed fullscreen content.")
mInterstitialAd = null
}
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.")
mInterstitialAd = null
}
override fun onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.")
}
override fun onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.")
}
}
mInterstitialAd?.show(this)
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
}
}
This is simply because you have implemented your if-else wrongly. You are loading ad only when you have interstitial instance, but as your if case is checking wrong condition, you are not going to initialise the instance anyway!
you need to verify the instance just before showing the Ad, not before initialising.
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
change your code to :
class MainActivity : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
private final var TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
adView?.loadAd(adRequest)
InterstitialAd.load(this, AD_UNIT_ID, adRequest, object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError.toString())
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d(TAG, "Ad was loaded")
mInterstitialAd = interstitialAd
}
})
mInterstitialAd?.fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.")
}
override fun onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
Log.d(TAG, "Ad dismissed fullscreen content.")
mInterstitialAd = null
}
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.")
mInterstitialAd = null
}
override fun onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.")
}
override fun onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.")
}
}
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
}
}

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)
}
}

AlertDialog in Android Studio Kotlin not displaying

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()
}

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
}
}
}

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