Toast.show() not showing the message in Emulator - android

This seems to work on Android 6 Marshmallow device Xiaomi Redmi 3S.
Seems like an emulator problem, but it isn't really misbehaving in any other sense.
I am a beginner in Android development and don't know much.
I have already confirmed that notifications for my app is ON.
Specs:
API Level : Android 4.4 (KitKat)
Android Studio version: 3.6.4
Emulator: Pixel XL API 28
All I attempted to do was a toast message would pop up telling how many times the button has been clicked.
Here's the MainActivity.kt:
class MainActivity : AppCompatActivity() {
private var greetingCount = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnToastMessage.setOnClickListener {
val suffix = when (++greetingCount) {
1 -> "st"
2 -> "nd"
3 -> "rd"
else -> "th"
}
val greetingMsg = "Welcome for the $greetingCount$suffix time(s)!"
Toast.makeText(this#MainActivity, greetingMsg, Toast.LENGTH_LONG).show()
Log.i(".MainActivity", "Clicked Button")
}
}
}
And here's the activity_main.xml file:
<?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"
android:padding="30dp">
<TextView
android:id="#+id/txtHelloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.314" />
<Button
android:id="#+id/btnToastMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.49"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtHelloWorld"
app:layout_constraintVertical_bias="0.49" />
</androidx.constraintlayout.widget.ConstraintLayout>

Didn't know this could be done, but wiping data and cold-booting the device fixed it.

Following are the steps you can follow (because I too got stuck):
Try restarting and cleaning your emulator device.
OR
You can run the app on your physical (android) device by setting the USB Debugging
option to True.

Related

Android Studio Kotlin variables

ok, brand new to android studio and kotlin (not programming in general)
installed Android Studio, set up a couple of hardware profiles (and enabled dev mode).
Here is my issue:
Simple app, 'every time you click the button, the number above doubles.'
in the first_fragment.xml file, I rename the ID to 'textDisplayedValue'
in the MainActivity.kt file, I create 2 variables originalValue and newValue.
When I try to set the originalValue to the value in textDisplayedValue, I get an 'Unresolved reference' error
Code
Log
In addition, when I launch the debugger, the 'ok' button is disabled. I assume that is due to the code errors so correct me if I am wrong.
Thanks in advance for the help.
Layout File
<?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=".FirstFragment">
<TextView
android:id="#+id/textDisplayedValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toTopOf="#id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/textDisplayedValue" />
</androidx.constraintlayout.widget.ConstraintLayout>
binding.fab.setOnClickListener { view ->
val originalValue = 1
val newValue = originalValue * 2
textDisplayedValue = newValue.toString()
Snackbar.make(view, "Value $originalValue changed to $newValue", Snackbar.LENGTH_LONG).show()
}
Try this
Comment the not working code
From the toolbar select
A. Build -> clean project
B. After that Build -> rebuild project
Uncomment the not working code and do this
val originalValue = binding.textDisplayedValue. text() .toString().toLong()
val newValue = originalValue * 2

Android Studio 'findViewById' no longer working

I am very new to Android/Kotlin. I have already created some programs and am making good progress.
But since today I have the problem that I can't get an 'findViewById' running even in the standard 'Hello World' program (Empty Activity).
I have only added the line android:id="#+id/myText" in the XML.
And in MainActivity.kt the line var myTxt = findViewById(android.R.id.myText).
But I get the error message Unresolved reference: 'myText'
The text 'myText' is red.
The usual attempts: Clear Cache, new project, ... I have already tried. The behavior is always the same.
In older projects 'findViewById' is working fine. But I find no difference in Import or settings between working and non working projects.
All in Android Studio 4.1.1
I am grateful for any help
Jan
<?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">
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.myhelloworld
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var myTxt = findViewById<TextView>(android.R.id.myText)
}
}
android.R.id.something is only used for android's own internal resources. You should remove that and it will work properly.
In kotlin you dont need to set findViewById instead you can just call the TextView name like this: myText.setText(userNameWithMsg)
android. was the problem! I removed it and all is fine again.
Thank you all! Must be a kind of copy paste error ;-))
Now I can go on .....
Great forum!
Thanks a lot
Jan

Android - Start CameraIntent activity for result crash without informations in emulator

I create an app that use camera. So I have a CameraIntent started as activity. startActivity(cameraIntent) works fine on every device and emulator I have, but when I use startActivityForResult(cameraIntent, 1), I've got a CameraApp crash on emulator with Pixel 2 and Pixel 3XL API 29. I tried on my real huawei device and on another emulator (nexus API 30) and it's working.
I cannot find any informations in logcat so I don't know where to look at to find the reason of the bug. I guess it's API 29 (or Pixel emulator ?) but I don't find any informations about this problem yet.
EDIT: I tried many versions and devices but this bug only happen on Pixel 2 with API 29. Does anyone have an idea of why ?
This is the code of the app I'm using to replicate the bug:
MainActivity.kt
private lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.button)
button.setOnClickListener {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (packageManager.resolveActivity(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY) == null) {
Toast.makeText(this, "no camera", Toast.LENGTH_SHORT).show()
return#setOnClickListener
}
startActivityForResult(cameraIntent, 1)
}
}
activity_main.xml (only a simple button)
<?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">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
(Sorry about my english.)
Thanks you for your help !
make sure that camera permission is attach in manifest file and permission granted by user here is the code of permission:
<uses-permission android:name="android.permission.CAMERA"
if enable multiple permission then prefer you to read the docmentation and use this dependency :
implementation 'com.karumi:dexter:6.2.1'
I found my answer: on the API 29, camera authorization need to be granted inside the app starting the camera intent. So I add <uses-permission android:name="android.permission.CAMERA" /> in the AndroidManifest.xml and ask for camera permission before launching the camera intent.

How do I properly make the dark mode settings menu work?

So I completed the first lesson of the Kotlin Course by Google on Udacity and after that I went on to make my own changes to the app that make them look better (just to learn, I don't care about the app). I made some changes like adding dark mode and customizing the UI.
I want the dark mode menu to work properly, like when I click on light mode it should recreate the activity with light mode enabled and should also check the light mode MenutItem. I also want the app to remember the settings so that if I choose Follow System during one session of the app and then close the app, it should keep following the system even after opening the app. I figured this should be done with SharedPreferences but I don't know how to properly do it. As you can see in the video attached below, when I click on any of the dark mode settings options, they don't automatically change the settings, I need to restart the app and only then do I see any changes in the activity that matches to whatever option I selected before closing the app.
Note: I want to mention that I am not very experienced with Android Development or Kotlin, I only started learning 2 months ago. I also want to mention that I DO NOT care about the app itself but I am rather using this app to learn how to get things done. I don't care if my app gets every feature I
would want it to have if I don't also learn how to do those things. It's not the app but the knowledge that I am getting from it that I care about, this is to say that please if you have an answer, do explain how that works.
This video shows the behavior of the app: https://drive.google.com/file/d/1SnN0r351OGF4xQNCtI1wtgouSFVROKzg/view?usp=sharing
I added a toolbar to my layout file of the main (and the only) activity. Here's the xml code for the layout resource:
<?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:id="#+id/diceRollerActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:title="#string/app_name" />
</com.google.android.material.appbar.AppBarLayout>
<ImageView
android:id="#+id/dice_image"
android:layout_width="275dp"
android:layout_height="335dp"
android:contentDescription="#+id/diceImage_imageView_description"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.395"
app:srcCompat="#drawable/empty_dice" />
<Button
android:id="#+id/roll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/Container_Button_Padding"
android:text="#string/roll"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="25sp"
app:backgroundTint="#color/bold_button_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/dice_image"
app:layout_constraintVertical_bias="0.32"
app:rippleColor="#color/button_ripple" />
</androidx.constraintlayout.widget.ConstraintLayout>
and here is my the Kotlin code for the same activity:
package com.example.diceroller
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.*
import androidx.appcompat.app.AppCompatDelegate
class MainActivity : AppCompatActivity() {
lateinit var diceImage: ImageView
lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.activity_toolbar))
val rollButton: Button = findViewById(R.id.roll_button)
diceImage = findViewById(R.id.dice_image)
rollButton.setOnClickListener {
rollDice()
}
sharedPreferences = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE)
when (sharedPreferences.getString("Night_Mode_State", getString(R.string.follow_system))) {
getString(R.string.follow_system) -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
getString(R.string.light_mode) -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
getString(R.string.dark_mode) -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.actionbar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.follow_system -> sharedPreferences.edit().putString("Night_Mode_State", getString(R.string.follow_system)).apply()
R.id.light_mode -> sharedPreferences.edit().putString("Night_Mode_State", getString(R.string.light_mode)).apply()
R.id.dark_mode -> sharedPreferences.edit().putString("Night_Mode_State", getString(R.string.dark_mode)).apply()
}
return true
}
private fun rollDice() {
when ((1..6).random()) {
1 -> diceImage.setImageResource(R.drawable.dice_1)
2 -> diceImage.setImageResource(R.drawable.dice_2)
3 -> diceImage.setImageResource(R.drawable.dice_3)
4 -> diceImage.setImageResource(R.drawable.dice_4)
5 -> diceImage.setImageResource(R.drawable.dice_5)
else -> diceImage.setImageResource(R.drawable.dice_6)
}
}
}
This gist includes other files that I think are required to answer this question properly, namely: The menu resource file, the colors resource file and the styles resource file: https://gist.github.com/sbeve72/36a71919f1f965c5dcd466db1e099b4f.js"

Kotlin Basic Cronometer Bug , Give Advice to Newbie

I have 2 button and 1 textview in my layout. I had just trained, but saw some bugs. When users starts the cronometer they can unlimited click on the start button how can i fix it ?
I'm really newbie in the android development. Can you give advices for me, while i was watching my udemy lesson, i could catch the codes and basics. After that, when i try to build some basic projects for improve my skills, it gets hard. I have many syntax errors. I know what to do, but I'm confusing the order.
What can i do to do get better ?
main_activity.kt
var runnable : Runnable = Runnable { }
var handler : Handler = Handler( )
var number = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Cronometer have bugs
// User can click the start button for unlimited
}
fun startTime(view: View) {
runnable = object : Runnable {
override fun run() {
number++
textView2.text = "$number"
handler.postDelayed(this,1000)
}
}
handler.post(runnable)
}
fun stopTime(view:View) {
handler.removeCallbacks(runnable)
}
}
```
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">
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:onClick="startTime"
android:text="START"
app:layout_constraintBaseline_toBaselineOf="#+id/button4"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="49dp"
android:layout_marginTop="88dp"
android:onClick="stopTime"
android:text="STOP"
app:layout_constraintStart_toEndOf="#+id/button3"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<TextView
android:id="#+id/textView2"
android:layout_width="180dp"
android:layout_height="40dp"
android:layout_marginTop="109dp"
android:gravity="center"
android:text="0"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Your question is not clear. If you want to prevent the user from clicking on the buttons more than once, you could disable them as soon as a click event is detected. For example, in your startTime method you could add
(view as Button).enabled = false
You need to cast your view to Button because the enabled property is not present in the View class (it comes from the TextView class actually, but Button inherits from it).
Then, you need to enable it again when you click on the stop button. You will need to retrieve a reference to your start button somehow, so you can access and enable it from your stopTime method. I'll leave that as an exercise for you ;).

Categories

Resources