KotlinNullPointerException for android::onClick - android

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

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

force close while intent from activity to activity

so i want to intent from settings activity into edit profile activity, but when i clicked the edit profile button in settings activity, suddenly my application is force closed. for the information, i have profile fragment attached to main activity. on profile fragment, it has button that intent to settings activity. but, in settings activity it also has button that intent to edit profile activity. the problem is i can't intent from the settings activity to edit profile activity.
here's the SettingsActivity.kt
class SettingsActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var settingsBinding: ActivitySettingsBinding
private var refUsers : DatabaseReference? = null
private var firebaseUser : FirebaseUser? = null
companion object{
fun getLaunchService (from: Context) = Intent(from, SettingsActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsBinding = ActivitySettingsBinding.inflate(layoutInflater)
setContentView(settingsBinding.root)
supportActionBar?.hide()
settingsBinding.cvSettingsLogOut.setOnClickListener(this)
settingsBinding.btnEditProfile.setOnClickListener(this)
userInfo()
}
private fun userInfo(){
firebaseUser = FirebaseAuth.getInstance().currentUser
refUsers = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser!!.uid)
refUsers!!.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
override fun onDataChange(snapshot: DataSnapshot) {
for (p0 in snapshot.children){
val userName = snapshot.child("userName").value.toString()
val email = snapshot.child("email").value.toString()
val profileImage = snapshot.child("profile_image").value.toString()
settingsBinding.tvProfileUsername.text = userName
settingsBinding.tvProfileEmail.text = email
Glide.with(this#SettingsActivity).load(profileImage).into(settingsBinding.ivProfileSettings)
}
}
})
}
override fun onClick(v: View) {
when(v.id){
R.id.btnEditProfile -> startActivity(EditProfileActivity.getLaunchService(this))
R.id.cvSettingsLogOut -> logOut()
}
}
private fun logOut() {
/* Create a new instance of the AlertDialog class. */
var alertDialog: AlertDialog? = null
val builder = AlertDialog.Builder(this)
/* Inflate the layout file for the dialog box. */
val view = DialogConfirmLogoutBinding.inflate(layoutInflater)
/* Set the view of the dialog box. */
builder.setView(view.root)
view.btnConfirmCancel.setOnClickListener {
alertDialog?.dismiss()
}
view.btnConfirmYes.setOnClickListener {
alertDialog?.dismiss()
FirebaseAuth.getInstance().signOut()
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
/* Showing the dialog box. */
alertDialog = builder.create()
alertDialog.show()
}
}
my EditProfileAcitivity.kt
class EditProfileActivity : AppCompatActivity() {
private lateinit var editProfileBinding: ActivityEditProfileBinding
companion object{
fun getLaunchService (from: Context) = Intent(from, EditProfileActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
editProfileBinding = ActivityEditProfileBinding.inflate(layoutInflater)
setContentView(editProfileBinding.root)
supportActionBar?.hide()
}
}
here's the layout for EditProfile 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=".activity.EditProfileActivity">
<ImageView
android:id="#+id/ivBackEditProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_20dp"
android:src="#drawable/ic_back"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/_20dp"
android:fontFamily="#font/poppins_medium"
android:text="#string/edit_profile"
android:textColor="#color/black"
android:textSize="#dimen/_18sp"
app:layout_constraintBottom_toBottomOf="#+id/ivBackEditProfile"
app:layout_constraintStart_toEndOf="#+id/ivBackEditProfile"
app:layout_constraintTop_toTopOf="#+id/ivBackEditProfile" />
<LinearLayout
android:id="#+id/llAddEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_20dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/ivBackEditProfile">
<ImageView
android:id="#+id/ivAddBgEditProfile"
android:layout_width="match_parent"
android:layout_height="#dimen/_150dp"
android:scaleType="fitXY"
android:src="#drawable/bg_addbgeditprofile">
</ImageView>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/ivAddProfilePhoto"
android:layout_width="#dimen/_100dp"
android:layout_height="#dimen/_100dp"
android:layout_marginStart="#dimen/_20dp"
android:scaleType="fitCenter"
android:src="#drawable/bg_addprofilephtoeditpro" />
</LinearLayout>
<EditText
android:id="#+id/etNameEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="#dimen/_25dp"
android:background="#drawable/bg_et_editprofile"
android:hint="Name"
android:layout_marginTop="#dimen/_20dp"
android:inputType="textPersonName"
android:maxLines="1"
android:maxLength="15"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/llAddEditProfile" />
<EditText
android:id="#+id/etBioEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_et_editprofile"
android:hint="Bio"
android:layout_marginHorizontal="#dimen/_25dp"
android:maxLines="3"
android:inputType="textMultiLine"
android:layout_marginTop="#dimen/_20dp"
android:maxLength="100"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/etNameEditProfile" />
<EditText
android:id="#+id/etLinkEditProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_et_editprofile"
android:hint="Link"
android:layout_marginHorizontal="#dimen/_25dp"
android:maxLines="1"
android:inputType="textUri"
android:layout_marginTop="#dimen/_20dp"
android:maxLength="15"
android:padding="#dimen/_15dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/etBioEditProfile" />
<Button
android:id="#+id/btnSaveEditProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="#dimen/_25dp"
android:layout_marginEnd="#dimen/_25dp"
android:background="#drawable/bg_btnaddpost"
android:fontFamily="#font/poppins_semibold"
android:paddingHorizontal="#dimen/_50dp"
android:text="Save"
android:textAllCaps="false"
android:textSize="#dimen/_18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
this is the log error that i got cuz of sudden force close on my app while intent to editprofile activity. if u know what's goin on with my code, pls help me. Thanks.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.isjieman.ocion, PID: 5334
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.isjieman.ocion/com.isjieman.ocion.activity.EditProfileActivity}: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
Caused by: android.view.InflateException: Binary XML file line #55 in com.isjieman.ocion:layout/activity_edit_profile: Error inflating class <unknown>
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:852)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1004)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1124)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at com.isjieman.ocion.databinding.ActivityEditProfileBinding.inflate(ActivityEditProfileBinding.java:80)
at com.isjieman.ocion.databinding.ActivityEditProfileBinding.inflate(ActivityEditProfileBinding.java:74)
at com.isjieman.ocion.activity.EditProfileActivity.onCreate(EditProfileActivity.kt:20)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalArgumentException: ScaleType FIT_CENTER not supported.
at de.hdodenhof.circleimageview.CircleImageView.setScaleType(CircleImageView.java:134)
at android.widget.ImageView.<init>(ImageView.java:223)
at android.widget.ImageView.<init>(ImageView.java:190)
at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:98)
at de.hdodenhof.circleimageview.CircleImageView.<init>(CircleImageView.java:94)
... 29 more
You are getting because you have set android:scaleType="fitCenter" in below code and CircleImageView not supporting fitCenter
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/ivAddProfilePhoto"
android:layout_width="#dimen/_100dp"
android:layout_height="#dimen/_100dp"
android:layout_marginStart="#dimen/_20dp"
android:scaleType="fitCenter"
android:src="#drawable/bg_addprofilephtoeditpro" />
kindly read limitation of library first
https://github.com/hdodenhof/CircleImageView#limitations

How add a spinner the navigation drawer in the fragment

I want to add a spinning top to the navigation drawer.I want it to look like this:
I couldn't find how and where to add.I always get this error when I try to find id
my spinner layout
<Spinner
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/qualitySpinner"
android:layout_marginLeft="50dp"
android:entries="#array/mQuality"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and my items
<item
android:id="#+id/right_menu_spinner"
android:icon="#drawable/icon_default"
android:title="Quality"
app:actionLayout="#layout/spinner_layout"/>
and my fragment code
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val array = arrayOf("deneme","deneme")
val denemeSp : Spinner = view.findViewById(R.id.qualitySpinner)
denemeSp.adapter = ArrayAdapter(view.context,android.R.layout.simple_spinner_item,array)
denemeSp.setOnItemSelectedListener(this)
}
but when it works it gives the following error:
2020-06-07 23:12:41.292 6872-6872/com.enesseval.moviedeneme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.enesseval.moviedeneme, PID: 6872
java.lang.IllegalStateException: view.findViewById(R.id.qualitySpinner) must not be null
at com.enesseval.moviedeneme.view.MoviesFragment.onViewCreated(MoviesFragment.kt:57)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:332)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2722)
at androidx.fragment.app.FragmentStateManager.activityCreated(FragmentStateManager.java:346)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1188)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
at android.app.Activity.performStart(Activity.java:7825)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-06-07 23:12:41.308 6872-6872/com.enesseval.moviedeneme I/Process: Sending signal. PID: 6872 SIG: 9
Your menu item should be something like (I edited the stock android studio Navigation project template for illustative purposes) :
<item
android:id="#+id/right_menu_spinner"
android:icon="#drawable/icon_default"
android:title="Quality"
app:actionViewClass="androidx.appcompat.widget.AppCompatSpinner"/>
And access in your Activity, not fragment :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup code ...
// Access Navigation header and menu
val navView: NavigationView = findViewById(R.id.nav_view)
(navView.menu.findItem(R.id.right_menu_spinner).actionView as Spinner).run {
adapter = ArrayAdapter(this#MainActivity, android.R.layout.simple_list_item_1, arrayOf("High", "Medium", "Low"))
}
}
}
Result :
Add you Spinner in XML:
<RelativeLayout
android:id="#+id/tilLanguage"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="35dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="35dp"
android:layout_weight=".28"
app:layout_constraintTop_toBottomOf="#+id/tvAlmostThere"
android:background="#drawable/spinner_background"
android:orientation="horizontal">
<Spinner
android:id="#+id/etLanguage"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginStart="5dp"
android:background="#android:color/transparent"
android:gravity="center"
android:spinnerMode="dropdown"
android:focusable="true"
android:textColorHint="#color/textColorPrimary"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:src="#drawable/dropdown" />
</RelativeLayout>
Add Strings for Values:
<item>Select Language:</item>
<item>English</item>
<item>French</item>
</string-array>
Then Add it in your Navigation Drawer:
Language = (Spinner) root.findViewById(R.id.etLanguage);
ArrayAdapter<CharSequence> status_adapter = ArrayAdapter.createFromResource(getActivity(), R.array.language_arrays, R.layout._spinner_item);
language_adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown);
Language .setAdapter(status_adapter);```

Getting Exception androidx.appcompat.widget.AppCompatTextView cannot be cast to android.view.TextureView

I am new to kotlin in android.
I followed this "https://codelabs.developers.google.com/codelabs/camerax-getting-started/#9" tutorial but got following error.
the app is built successfully however, app stops and the message on my phone says "app keeps stopping".
I also followed the tutorial in here https://developer.android.com/training/camera
but no luck, it starts but do not capture any image. All i wanna do is to get frame from realtime video stream and work on frames. Any help.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 28612
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.view.TextureView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.view.TextureView
at com.example.myapplication.MainActivity.onCreate(MainActivity.kt:40)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6944) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
My xml is
<?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/view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ImageButton
android:id="#+id/capture_button"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_margin="24dp"
app:srcCompat="#android:drawable/ic_menu_camera"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
and my main is
// This is an arbitrary number we are using to keep track of the permission
// request. Where an app has multiple context for requesting permission,
// this can help differentiate the different contexts.
private const val REQUEST_CODE_PERMISSIONS = 10
// This is an array of all the permission specified in the manifest.
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Add this at the end of onCreate function
viewFinder = findViewById(R.id.view_finder)
// Request camera permissions
if (allPermissionsGranted()) {
viewFinder.post { startCamera() }
} else {
ActivityCompat.requestPermissions(
this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
// Every time the provided texture view changes, recompute layout
viewFinder.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
updateTransform()
}
}
// Add this after onCreate
private val executor = Executors.newSingleThreadExecutor()
private lateinit var viewFinder: TextureView
private fun startCamera() {
...
}
.....
}
}
Your view_finder view in the layout of MainActivity is AppCompatTextView and you are trying to assign it into a TextureView here:
viewFinder = findViewById(R.id.view_finder)
Change one of them to match the other.
<?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">
<TextureView //changed from textView to TextureView
android:id="#+id/view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/capture_button"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_margin="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#android:drawable/ic_menu_camera" />
</androidx.constraintlayout.widget.ConstraintLayout>

How to disable a button in Kotlin?

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

Categories

Resources