How to disable a button in Kotlin? - android

I have created 2 activities, well the first one I use it as splash screen, now in the second one I have difficulties when deactivating a button, I leave the code for your understanding
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TemaCalcActivity">
<Spinner
android:layout_width="144dp"
android:layout_height="39dp"
android:id="#+id/spnDiferencia" app:layout_constraintEnd_toEndOf="parent"
android:layout_marginStart="8dp" app:layout_constraintStart_toEndOf="#+id/spnMP"
android:layout_marginEnd="8dp" android:layout_marginTop="24dp"
app:layout_constraintTop_toBottomOf="#+id/textView5"/>
<Button
android:text="OK"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/button" app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="120dp"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="120dp" android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="#+id/spnMP" android:background="#drawable/button_effect"
android:textSize="18sp" android:textStyle="bold" android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="0.026" android:onClick="onBotonFinalizar" android:enabled="false"/>
</android.support.constraint.ConstraintLayout>
Main2Activity.kt
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
spnDiferencia.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
when (position) {
0 -> { button.isEnabled = true}
1 -> { button.isEnabled = false}
}
}
The error I have is that the entire application is stopped and then restarted, making this a repetition.
button.isEnabled = true
// or
button.isClickable = true
caution ---> button == btnCalcular
--- error log ---
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mrl.fr.tuto, PID: 22066
java.lang.IllegalStateException: btnCalcular must not be null
at com.mrl.fr.tuto.Main2Activity$onCreate$5.onItemSelected(Main2cActivity.kt:128)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:919)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:908)
at android.widget.AdapterView.access$300(AdapterView.java:53)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:878)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5631)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

Just to disable a button .
button.isEnabled = false
button.isClickable = false
and If you want to disable a button , and want to grey out its color & background ,you can do something like this -
fun markButtonDisable(button: Button) {
button?.isEnabled = false
button?.setTextColor(ContextCompat.getColor(textView.context, R.color.white))
button?.setBackgroundColor(ContextCompat.getColor(textView.context, R.color.greyish))
}

Did you try this
myButton.setEnabled(false);

Related

kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized

my application is giving the below error that you mentioned above and it says there is an error on line 69, but you have tried all the solutions and could not fix it. You are new to programming and trying to learn, so you are asking for help from experienced people like us.
Can you please help me?
Error Message:
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kotlincountries, PID: 15240
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
at com.example.kotlincountries.adapter.CountryAdapter.onCountryClicked(CountryAdapter.kt:69)
at com.example.kotlincountries.databinding.ItemCountryBindingImpl$OnClickListenerImpl.onClick(ItemCountryBindingImpl.java:173)
at android.view.View.performClick(View.java:7506)
at android.view.View.performClickInternal(View.java:7483)
at android.view.View.-$$Nest$mperformClickInternal(Unknown Source:0)
at android.view.View$PerformClick.run(View.java:29334)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
I have enabled two options in my gradle file.
buildFeatures {
viewBinding = true
dataBinding = true
}
I checked the connections in the XML file.
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="country"
type="com.example.kotlincountries.model.Country" />
<variable
name="listener"
type="com.example.kotlincountries.adapter.CountryClickListener" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:onClick="#{listener::onCountryClicked}"
android:orientation="horizontal">
<TextView
android:id="#+id/countryUuidText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="#{String.valueOf(country.uuid)}">
</TextView>
<ImageView
android:id="#+id/imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:padding="3dp"
android:downloadUrl="#{country.imageUrl}">
</ImageView>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical"
android:layout_weight="3">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{country.countryName}"
android:padding="5dp"
android:textSize="18sp"
android:textStyle="bold">
</TextView>
<TextView
android:id="#+id/region"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{country.countryRegion}"
android:textSize="16sp"
android:padding="5dp">
</TextView>
</LinearLayout>
</LinearLayout>
</layout>
I checked the data I fetched in my adapter class.
class CountryAdapter(val countryList:ArrayList<Country>): RecyclerView.Adapter<CountryAdapter.CountryViewHolder>(),CountryClickListener {
private lateinit var binding : ItemCountryBinding
class CountryViewHolder(var view:ItemCountryBinding) :RecyclerView.ViewHolder(view.root) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CountryViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemCountryBinding.inflate(inflater, parent, false)
return CountryViewHolder(binding)
}
override fun getItemCount(): Int {
return countryList.size
}
override fun onBindViewHolder(holder: CountryViewHolder, position: Int) {
holder.view.country=countryList[position]
holder.view.listener=this
}
fun updateCountryList(newCountryList:List<Country>){
countryList.clear()
countryList.addAll(newCountryList)
notifyDataSetChanged()
}
override fun onCountryClicked(v: View) {
val uuid=binding.countryUuidText.text.toString().toInt()
val action=FeedFragmentDirections.actionFeedFragmentToCountryFragment(uuid)
Navigation.findNavController(v).navigate(action)
}
}
Could you please help me? I couldn't find a solution even though I checked the connections in my XML file, verified the data in my adapter class.
Error message is clear that binding variable which is declared as lateinit is not initialised and tried to use it in your adapter class .
and if you will check your code of adapter (as location mentioned in error) you will get that problem is in onCreateViewHolder
So just change in onCreateViewHolder method of adapter
From
val binding = ItemCountryBinding.inflate(inflater, parent, false)
To
binding = ItemCountryBinding.inflate(inflater, parent, false)
i have just removed val as you have already declared binding

Can a Kotlin entity with a constructor that has default non null values become null at runtime?

I have spent the last couple of weeks trying to rewrite an android app from a java to kotlin, from custom fragment navigation to navigation component and all other Jetpack bells and whistles.
Now I've encountered several bugs through this process but there's this specific one. I have a kotlin class with a default constructor as shown below
#Entity(tableName = Globals.FIREBASE_ITEM_NODE)
#Parcelize
class Item(
#PrimaryKey(autoGenerate = true)
var id: Int = 0 ,
var imageUri: String = "",
var isRead: Boolean = false,
var expanded: Boolean = false,
var favourite: Boolean = false,
var isSaved: Boolean = false,
var englishWord: String = "",
var topic: String = "",
var audioUri: String = "",
var rutooroWord: String = "",
var firebaseImageNode: String = "",
) : Parcelable
This is because I fetch data from firebase rtdb and cache it in room. I then collect a flow of this data submit it to a List Adapter and use databinding to bind it to my views.
the item Viewholder
inner class ItemViewHolder(private val b: RvLangItemBinding) : RecyclerView.ViewHolder(b.root) {
fun bind(position: Int) {
if (getItem(position) !is Item) return
b.item = getItem(position) as Item
if ((getItem(position) as Item).expanded) createPalette(
(getItem(position) as Item).imageUri,
b.parent,
b.tvEnglish,
b.tvRutooro
)
else b.parent.setBackgroundColor(
itemView.context.resources.getColor(
R.color.transparent,
itemView.context.theme
)
)
b.root.setOnClickListener {
(getItem(position) as Item).expanded = !(getItem(position) as Item).expanded
notifyItemChanged(position)
if (prevPosition != INITIAL_POSITION && prevPosition != position) {
(getItem(prevPosition) as Item).expanded = false
notifyItemChanged(prevPosition)
}
prevPosition = position
if ((getItem(position) as Item).expanded && (getItem(position) as Item).audioUri.isNotEmpty())
AudioUtil.playAudioFile(
itemView.context,
Uri.parse((getItem(position) as Item).audioUri)
)
}
b.favourite.setOnLikeListener(object : OnLikeListener {
override fun liked(likeButton: LikeButton) {
(getItem(position) as Item).favourite = true
onItem.update(getItem(position) as Item)
}
override fun unLiked(likeButton: LikeButton) {
(getItem(position) as Item).favourite = false
onItem.update(getItem(position) as Item)
}
})
b.audioButton.setOnClickListener {
if ((getItem(position) as Item).audioUri.isNotEmpty())
AudioUtil.playAudioFile(
itemView.context,
Uri.parse((getItem(position) as Item).audioUri)
)
}
}
}
and this is the xml for the item
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<import type="android.view.View" />
<variable
name="item"
type="com.allez.san.learnrutooro.models.Item" />
</data>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="18dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="18dp"
android:elevation="4dp"
android:padding="8dp"
app:cardCornerRadius="4dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textview.MaterialTextView
android:id="#+id/tv_english"
style="#style/TextAppearance.Material3.TitleMedium"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="#{item.englishWord}"
android:textSize="16sp"
app:layout_constraintEnd_toStartOf="#id/favourite"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Good Morning" />
<com.like.LikeButton
android:id="#+id/favourite"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginEnd="4dp"
app:icon_size="25dp"
app:icon_type="star"
app:liked="#{item.favourite}"
app:layout_constraintBottom_toBottomOf="#+id/tv_english"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="#+id/tv_english"
app:like_drawable="#drawable/ic_star_green"
app:unlike_drawable="#drawable/ic_star_white" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="0dp"
android:layout_height="1dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
android:background="#android:color/darker_gray"
app:layout_constraintBottom_toBottomOf="#id/downArrow"
app:layout_constraintEnd_toStartOf="#id/downArrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#id/downArrow" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/downArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:src="#drawable/ic_arrow_drop_down"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/favourite" />
<com.google.android.material.textview.MaterialTextView
android:id="#+id/tv_rutooro"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:text="#{item.rutooroWord}"
android:textSize="16sp"
android:visibility="#{item.expanded? View.VISIBLE:View.GONE}"
app:layout_constraintBottom_toTopOf="#id/item_image"
app:layout_goneMarginBottom="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/downArrow"
tools:text="oraire ota" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/item_image"
setImage="#{item.imageUri}"
setImageItemVisibility="#{item}"
android:layout_width="270dp"
android:layout_height="200dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/tv_rutooro"
app:layout_goneMarginBottom="16dp"
tools:src="#drawable/lr_logo_light" />
<com.google.android.material.imageview.ShapeableImageView
android:id="#+id/audio_button"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:src="#drawable/ic_audio"
android:visibility="#{item.expanded? View.VISIBLE:View.GONE}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/downArrow"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</layout>
and these are my binding adapters
#BindingAdapter("setImage")
fun setImage(view:ImageView, uri: String)=
Glide.with(view).load(uri).into(view)
#BindingAdapter("setImageItemVisibility")
fun setItemImageVisibility(view:ImageView, item: Item){
view.visibility = if(item.expanded && item.imageUri.isNotEmpty()) View.VISIBLE else View.GONE
}
and this is the error I've been getting.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.allez.san.myapplication, PID: 26721
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter item
at com.allez.san.learnrutooro.utils.BindingUtilsKt.setItemImageVisibility(Unknown Source:7)
at com.allez.san.learnrutooro.databinding.RvLangItemBindingImpl.executeBindings(RvLangItemBindingImpl.java:152)
at androidx.databinding.ViewDataBinding.executeBindingsInternal(ViewDataBinding.java:512)
at androidx.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:484)
at androidx.databinding.ViewDataBinding$7.run(ViewDataBinding.java:218)
at androidx.databinding.ViewDataBinding$8.doFrame(ViewDataBinding.java:320)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1106)
at android.view.Choreographer.doCallbacks(Choreographer.java:866)
at android.view.Choreographer.doFrame(Choreographer.java:792)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1092)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
I/Process: Sending signal. PID: 26721 SIG: 9
How is this possible and why??? I've been at it for a while now. reading as much as I could about the subject but no luck yet.
Any help will be appreciated. thanx in advance.
try to change the fields type to nullable and run it again, if you did not have the same error then the problem is that you defined entity all its fields are non-nullable, so when you are calling #Query("SELECT * FROM items") fun getAllItems(): Flow<List<Item>> you are trying to give a null value from database to one of the fields.
I think the problem was with my binding adapters
#BindingAdapter("setImage")
fun setImage(view: ImageView, uri: String) =
Glide.with(view).load(uri).into(view)
#BindingAdapter("setImageItemVisibility")
fun setItemImageVisibility(view: ImageView, item: Item) {
view.visibility = if (item.expanded && item.imageUri.isNotEmpty()) View.VISIBLE else View.GONE
}
Because when i switched to directly binding the image and setting the image visibility in the item viewholder everything is working just fine.
Glide.with(itemView).load((getItem(position) as Item).imageUri).into(b.itemImage)
b.itemImage.visibility = if ((getItem(position) as Item).expanded && (getItem(position) as Item).imageUri.isNotEmpty()) View.VISIBLE else View.GONE
I don't think this is a solution to that error coz I still don't know why I was getting it and I'd like to still use databinding to set the image and its visibility. If anyone has an explanation as to why this was happening I'd really appreciate it.

KotlinNullPointerException for android::onClick

I`m just started learning Kotlin, and i have a problem with one of the buttons.
In MainActivity i have a button, that shows a popup with EditText and Button. In that popup user enters a city, and variable CITY changes according to user input after pressing a button.
In function cityChange im trying to replace my variable CITY with a text that user enters in EditText named editText. But when user taps on button, my program crashes with a NullPointerException. Can someone explain, or show how to fix that problem?
Exception log
FATAL EXCEPTION: main
Process: com.example.weatherapp, PID: 16567
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:7192) 
at android.view.View.performClickInternal(View.java:7166) 
at android.view.View.access$3500(View.java:824) 
at android.view.View$PerformClick.run(View.java:27592) 
at android.os.Handler.handleCallback(Handler.java:888) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:213) 
at android.app.ActivityThread.main(ActivityThread.java:8178) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101) 
Caused by: kotlin.KotlinNullPointerException
at com.example.weatherapp.MainActivity.cityChange(MainActivity.kt:48)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:7192) 
at android.view.View.performClickInternal(View.java:7166) 
at android.view.View.access$3500(View.java:824) 
at android.view.View$PerformClick.run(View.java:27592) 
at android.os.Handler.handleCallback(Handler.java:888) 
at android.os.Handler.dispatchMessage(Handler.java:100) 
at android.os.Looper.loop(Looper.java:213) 
at android.app.ActivityThread.main(ActivityThread.java:8178) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101) 
I/Process: Sending signal. PID: 16567 SIG: 9
MainActivity.kt
class MainActivity : AppCompatActivity() {
var CITY: String = "kyiv, ua"
val API: String = "7c45088f48678b739d4d8409a2d9d03e"
private var btn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val menuActivity = findViewById<Button>(R.id.activityButton)
menuActivity.setOnClickListener(){
val Intent = Intent(this, MenuActivity::class.java)
startActivity(Intent)
}
var dialog = CustomDialogFragment()
val clkBtn = findViewById<Button>(R.id.cityChange)
clkBtn.setOnClickListener {
dialog.show(supportFragmentManager, "customDialog")
}
}
fun cityChange(view: View){
btn = findViewById(R.id.changingButton)
btn!!.setOnClickListener{
CITY = editText.text.toString()
}
}
change_city.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="200dp"
android:background="#color/colorPrimaryDark"
android:padding="5dp"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City Change"
android:textStyle="bold"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:gravity="center"
android:inputType="textPersonName"
android:text="" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="225dp"
android:orientation="vertical">
<Button
android:onClick="cityChange"
android:id="#+id/changingButton"
android:layout_width="match_parent"
android:layout_height="62dp"
android:layout_gravity="bottom"
android:background="#color/bluelight"
android:text="Submit" />
</LinearLayout>
</LinearLayout>
Just simply do this
// Variable declaration
private var btn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val menuActivity = findViewById<Button>(R.id.activityButton)
menuActivity.setOnClickListener(){
val Intent = Intent(this, MenuActivity::class.java)
startActivity(Intent)
}
var dialog = CustomDialogFragment()
btn= findViewById<Button>(R.id.changingButton)
clkBtn.setOnClickListener {
dialog.show(supportFragmentManager, "customDialog")
}
}
Or Else You have to Change
This
val clkBtn = findViewById<Button>(R.id.cityChange)
To
val clkBtn = findViewById<Button>(R.id.changingButton)
Hope this will helpful to you.
wrong ID
from this
val clkBtn = findViewById<Button>(R.id.cityChange)
to
val clkBtn = findViewById<Button>(R.id.changingButton)
in your XML the button id is "changingButton" not "cityChange"
and don't use onClick and setOnClickListener together, just choose one

How to change the text on the second activity on button clicked from first activity? [KOTLIN]

I have to implement OTP validation on my application, I just want to get the mobile number from the previous activity and set it to the textview on the next activity once I clicked the Next Button intent from Activity 1 to Activity 2.
Here is how it looks like in view:
I would like to put the mobile number below the please enter the otp that has sent to..
First try: I called the ObjectSingleton.mobileNum since it carries the mobile # then I used mobileNum.setText(ObjectSingleton.mobileNum) but it ddint work.
My codes in 1st Activity where intent is happening to go to the next Activity;
class MobileNumberActivity : AppCompatActivity(), OtpInterface.MobileNumberViews {
lateinit var presenterMobileNumber:MobileNumberPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mobile_number)
presenterMobileNumber = MobileNumberPresenter()
presenterMobileNumber.mobileViews = this
close_icon2.setOnClickListener {
finish()
}
nxtBtn.setOnClickListener {
if (inputText.text.isNullOrEmpty()) {
inputText.error = "Please enter valid mobile number."
} else if (inputText.text.toString().length != 10) {
inputText.error = "Please enter valid mobile number."
} else{
val mobile = inputText.text.toString()
presenterMobileNumber.otpMobile(mobile)
}
}
}
override fun ifFailed(msg: String) {
errorMsg.setText(msg)
}
override fun ifSuccess(res: OtpData) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
startActivity(intent)
}
Here are the codes of the 2nd Acitivy where I want to change the text of mobile number display
class OtpValidationActivity : AppCompatActivity(), OtpValidateInterface.OtpValidateViews {
lateinit var otpPresenter: OtpPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_otp_verification)
otpPresenter = OtpPresenter()
otpPresenter.otpValidationViews = this
verifyOtpBtn.setOnClickListener {
if (otp_input.text.isNullOrEmpty()) {
otp_input.error = "Please enter OTP."
} else{
val otpNumber = otp_input.text.toString()
otpPresenter.otpValidate(ObjectSingleton.mobileNum,otpNumber)
}
}
}
override fun validateFailed(res: String) {
resend.setText("Failed")
}
override fun validateSuccess(msg: OtpValidationData) {
resend.setText("Success")
}
For your REFERENCE here's the XML file of the said PICTURE above where should I put the Mobile number.
<?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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/rectangle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="372dp"
android:layout_height="wrap_content"
android:background="#drawable/otpbg"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.041">
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_30sdp"
android:text="OTP VERIFICATION"
android:textColor="#color/reply_black_800"
android:textSize="#dimen/_22sdp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please enter the OTP that has sent to">
</TextView>
<TextView
android:id="#+id/mobileNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_22sdp"
android:layout_marginBottom="#dimen/_30sdp"
android:text="#string/_63"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/_19sdp"
android:textStyle="bold">
</TextView>
</LinearLayout>
<com.mukesh.OtpView
android:id="#+id/otp_input"
android:layout_width="267dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:inputType="number"
android:textAppearance="?attr/textAppearanceHeadline5"
android:textColor="#android:color/black"
app:OtpItemCount="6"
app:OtpItemWidth="#dimen/_30sdp"
app:OtpLineColor="#color/reply_black_800"
app:OtpViewType="line" />
<TextView
android:id="#+id/resend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_19sdp"
android:gravity="center"
android:textSize="#dimen/_14sdp"
android:text="#string/didn_t_recieve_the_code_resend_code"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/otp_view"
app:layout_constraintVertical_bias="0.039"
android:paddingBottom="#dimen/_30sdp"/>
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/verifyOtpBtn"
android:layout_width="378dp"
android:layout_height="42dp"
android:background="#drawable/radius_btn"
android:backgroundTint="#color/colorPrimary"
android:text="Next"
android:textAllCaps="false"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.484"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearLayout6"
app:layout_constraintVertical_bias="0.117" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am new to Kotlin/Android Develepment I hope someone help me with this.
#JUniorDEV
UPDATE: Imma share to you my MobileNumberPresenter codes:
var mobileViews:OtpInterface.MobileNumberViews? = null
override fun otpMobile(mobile: String) {
Fuel.post("https://api.staging.riderko.com/riderko_be/public/api/riderSendRegisterOtp", listOf(
"mobile" to mobile
)).timeout(5000)
.header("Accept", "application/json")
.responseObject<OtpResponse>{request, response, result ->
when (result) {
is Result.Failure -> {
mobileViews?.ifFailed(result.error.response.statusCode.toString())
}
is Result.Success -> {
val (bytes, error) = result
if (bytes != null) {
val status = bytes.success
if (status){
mobileViews?.ifSuccess(bytes.data)
}else{
mobileViews?.ifFailed(bytes.message)
}
}
}
}
}
}
in OtpInterface.MobileNumberViews
add second parameter as string to ifSuccess
in MobileNumberPresenter
change mobileViews?.ifSuccess(bytes.data) to mobileViews?.ifSuccess(bytes.data, mobile)
and you ifSuccess method will be changed to
override fun ifSuccess(res: OtpData, mobileNum: String) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
intent.putExtra("MOBILE_NUMBER",mobileNum)
startActivity(intent)
}
And in OtpValidationActivity
val mobileNum = arguments?.getString("MOBILE_NUMBER")
Update the code of 1st activity to
override fun ifSuccess(res: OtpData) {
errorMsg.setText("Sent!")
var intent = Intent(this, OtpValidationActivity::class.java)
startActivity(intent)
intent.putExtra("MobileNum",mobile)
}
Now in the second activity after setContentView(R.layout.activity_otp_verification)
add this line:
val MobNo = intent.getExtra("MobileNum")
mobileNum.text = MobNo
Hope this will work
Here in the MobileNumberActivity inside the ifSuccess() before you do startActivity(intent) do intent.putExtra("IDENTIFER",mobileNum)
Now in the 2nd activity simply do val mobNO = intent.getStringExtra("IDENTIFER")
and now assign the mobNo to the desired textView.
This helps pass data between activities.
I was able to solve this simply by calling ObjectSingleton.mobNum assigned to a variable and displayed it into view I just learnt that once objectsingleton has been assigned to, the value will be carried over to any part of your app, this value will be removed automatically when you close your app.

BottomSheet is jumping on button clicks

I have a BottomSheet which houses a product detail card. The problem is, when I click on the + or - button on the product detail while the bottom sheet is in it's Expanded state, it jumps down.
When it is down and I click on the buttons it doesn't jump, it only happens when it is in it's Expanded (completely up) state
I have attached a GIF to show what is exactly happening
Here is the code
scan_sheet.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:id="#+id/bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:animateLayoutChanges="false"
android:background="#drawable/bottom_sheet_dialog_fragment"
android:orientation="vertical"
app:behavior_hideable="true"
app:behavior_peekHeight="100dp"
app:layout_behavior="studio.monotype.storedemo.BottomSheetBehavior">
<include
layout="#layout/hero_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/divider_view"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_marginStart="24dp"
android:layout_marginTop="44dp"
android:layout_marginEnd="24dp"
android:background="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/hero_item" />
<include
layout="#layout/related_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/divider_view"
tools:layout_editor_absoluteX="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
ScanActivity.kt (simplified to show only what is essential)
class ScanActivity : AppCompatActivity() {
private lateinit var bottomSheet: BottomSheetBehavior<*>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scan)
setupBottomSheet()
showSheet()
}
private fun setupBottomSheet() {
bottomSheet = BottomSheetBehavior.from(bottom_sheet)
bottomSheet.isHideable = true
bottomSheet.skipCollapsed= true
bottomSheet.isDraggable = true
bottomSheet.state = BottomSheetBehavior.STATE_HIDDEN
bottomSheet.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
#SuppressLint("SwitchIntDef")
override fun onStateChanged(sheet: View, newState: Int) {
when (newState) {
BottomSheetBehavior.STATE_HIDDEN -> {
codeScanner.startPreview()
}
}
}
})
plus_btn.setOnClickListener {
var qty= qty_tv.text.toString().toInt()
qty++
qty_tv.text =qty.toString()
}
minus_btn.setOnClickListener {
var qty= qty_tv.text.toString().toInt()
if(qty!=0)
{
qty--
}
qty_tv.text =qty.toString()
}
}
private fun showSheet() {
bottomSheet.state = BottomSheetBehavior.STATE_EXPANDED
}
}
it seems that google engineer gave correct answer
Seems like something is going on because you are setting
android:layout_gravity="bottom" on the view with the
BottomSheetBehavior. You should remove that line.
It helped on my case
Looks to me like that could be a bug in the BottomSheetBehavior? Seems like the height of the sheet isn't getting saved or restored correctly. After the button is pressed, a layout happens again which changes the height. Could you file a bug at https://issuetracker.google.com/issues/new?component=439535

Categories

Resources