ViewBinding with generated CustomViews in Android | android.view.InflateException - android

I am referring to both questions:
Android ViewBinding with CustomView and
How to use View Binding on custom views
I am currently migrating from Kotlin synthetics to view binding and I am using alot of custom generated views, mainly to ajust the view size when pressed. It looks like the following (prior to that was java code, if I did something wrong while switching to kotlin please feel free to correct me):
class CustomButton constructor(context: Context, attrs: AttributeSet?): AppCompatButton(context, attrs) {
#SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (event.action == MotionEvent.ACTION_CANCEL) {
val regainer =
AnimatorInflater.loadAnimator(context, R.animator.regain_size) as AnimatorSet
regainer.setTarget(this)
regainer.start()
return true
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val reducer = AnimatorInflater.loadAnimator(context, R.animator.reduce_size) as AnimatorSet
reducer.setTarget(this)
reducer.start()
return true
}
MotionEvent.ACTION_UP -> {
val regainer = AnimatorInflater.loadAnimator(context, R.animator.regain_size) as AnimatorSet
regainer.setTarget(this)
regainer.start()
return true
}
}
return false
}
override fun performClick(): Boolean {
super.performClick()
return true
}
Unfortunatly all the questions I looked up so far only reffer to a solution including a custom .xml file. My binding in the activity looks like this:
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.customButton.//...
}
What I am currently getting is an android.view.InflateException through that custom view. Does anyone have an idea on how to implement view binding in this case or how to initialize it in the CustomButton class? Any help with this is much appreciated!
Best regards,
Markus
This is the stack trace of the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.app, PID: 13035
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.app/com.my.app.MainActivity}: android.view.InflateException: Binary XML file line #39 in com.my.app:layout/activity_main: Binary XML file line #39 in com.my.app:layout/activity_main: Error inflating class com.my.app.custom.CustomTextView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3611)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3775)
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:2246)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:233)
at android.app.ActivityThread.main(ActivityThread.java:8010)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
Caused by: android.view.InflateException: Binary XML file line #39 in com.my.app:layout/activity_main: Binary XML file line #39 in com.my.app:layout/activity_main: Error inflating class com.my.app.custom.CustomTextView
Caused by: android.view.InflateException: Binary XML file line #39 in com.my.app:layout/activity_main: Error inflating class com.my.app.custom.CustomTextView
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.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at com.my.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:78)
at com.my.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:72)
at com.my.app.MainActivity.onCreate(MainActivity.kt:59)
at android.app.Activity.performCreate(Activity.java:8006)
at android.app.Activity.performCreate(Activity.java:7990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3584)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3775)
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:2246)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:233)
at android.app.ActivityThread.main(ActivityThread.java:8010)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f0302ca a=-1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:625)
at android.widget.TextView.readTextAppearance(TextView.java:4000)
E/AndroidRuntime: at android.widget.TextView.<init>(TextView.java:1093)
at android.widget.TextView.<init>(TextView.java:994)
at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:102)
at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:97)
at com.my.app.custom.CustomTextView.<init>(CustomTextView.kt:13)
... 27 more
CustomTextView.kt:13 is this line:
class CustomTextView constructor(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
MainActivity.kt:59 is this line:
binding = ActivityMainBinding.inflate(layoutInflater)
The activity_main.xml looks like this:
<?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"
android:fillViewport="true"
app:layout_constrainedHeight="true"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.Guideline
android:id="#+id/mainGuidelineVerticalLeft"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.05"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/mainGuidelineVerticalRight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.95"/>
<com.my.app.custom.CustomTextView
android:id="#+id/mainSubmenuSettings"
android:layout_width="wrap_content"
android:layout_height="#dimen/minimum"
android:gravity="center"
android:paddingHorizontal="12dp"
android:layout_marginEnd="12dp"
android:text="#string/textViewSettings"
android:textColor="?attr/primaryTextColorDefault"
android:textSize="#dimen/textViewS"
android:textStyle="bold"
android:focusable="true"
android:clickable="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<com.my.app.custom.CustomCardView
android:id="#+id/mainCardView1"
android:layout_width="0dp"
android:layout_height="#dimen/cardViewHeightLarge"
android:layout_marginVertical="#dimen/cardViewMarginVertical"
android:clickable="true"
android:focusable="true"
android:elevation="#dimen/elevation"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="#dimen/cardViewCornerRadiusLarge"
app:cardUseCompatPadding="true"
app:layout_constraintBottom_toTopOf="#id/mainCardView2"
app:layout_constraintEnd_toStartOf="#+id/mainGuidelineVerticalRight"
app:layout_constraintStart_toStartOf="#+id/mainGuidelineVerticalLeft"
app:layout_constraintVertical_chainStyle="packed">
</com.my.app.custom.CustomCardView>
<com.my.app.custom.CustomCardView
android:id="#+id/mainCardView2"
android:layout_width="0dp"
android:layout_height="#dimen/cardViewHeightLarge"
android:layout_marginTop="#dimen/cardViewMarginVertical"
android:layout_marginBottom="10dp"
android:clickable="true"
android:focusable="true"
android:elevation="#dimen/elevation"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="#dimen/cardViewCornerRadiusLarge"
app:cardUseCompatPadding="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/mainGuidelineVerticalRight"
app:layout_constraintStart_toStartOf="#+id/mainGuidelineVerticalLeft"
app:layout_constraintVertical_chainStyle="packed">
</com.my.app.custom.CustomCardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Nothing in the stack trace points to View Binding as being the problem here. Instead, it looks like a theme issue:
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 5: TypedValue{t=0x2/d=0x7f0302ca a=-1}
at android.content.res.TypedArray.getColorStateList(TypedArray.java:625)
at android.widget.TextView.readTextAppearance(TextView.java:4000)
The first place I'd look is here:
<com.my.app.custom.CustomTextView
android:textColor="?attr/primaryTextColorDefault"
... />
Make sure that you actually define <item name="primaryTextColorDefault"> in your theme.

Related

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

Wear OS - settting up project with fragments

I'm trying to set up a Wear OS project. I have some experience with normal android development but Wear os is new for me.
I'm used to just having one MainActivity and some fragments. But I'm trying to make that work for Wear OS but with no success. It keeps crashing when I want to use viewBinding in the OverviewFragment.kt.
I got the following project now:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.BoxInsetLayout 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"
android:padding="#dimen/box_inset_layout_padding"
tools:context=".MainActivity"
tools:deviceIds="wear">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/inner_frame_layout_padding"
app:layout_boxedEdges="left|right">
<include
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</androidx.wear.widget.BoxInsetLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph" />
</androidx.wear.widget.BoxInsetLayout>
fragment_overview.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.OverviewFragment">
<TextView
android:id="#+id/tvOverview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:text="overview"
android:textAlignment="center" />
</FrameLayout>
MainActivity.kt
class MainActivity : FragmentActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
OverviewFragment.kt
class OverviewFragment : Fragment() {
private var _binding: FragmentOverviewBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_overview, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvOverview.setOnClickListener {
println("great")
}
}
}
Just a simple design, but it does not like the binding.tvOverview.setOnClickListener part in OverviewFragment.kt. It just keeps crashing.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.krakert.tracker, PID: 7261
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.krakert.tracker/com.krakert.tracker.MainActivity}: android.view.InflateException: Binary XML file line #17: Binary XML file line #8: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #17: Binary XML file line #8: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
Caused by: java.lang.NullPointerException
at com.krakert.tracker.ui.OverviewFragment.getBinding(OverviewFragment.kt:15)
at com.krakert.tracker.ui.OverviewFragment.onViewCreated(OverviewFragment.kt:28)
I would like some help here, setting the project up. Really new to Wear OS
Thanks!
Not sure how this can work and suspect this is where the NullPointerException comes from
private var _binding: FragmentOverviewBinding? = null
private val binding get() = _binding!!
compare to the example at https://developer.android.com/topic/libraries/view-binding#fragments
which sets _binding in onCreateView

Starting a fragment with a recyclerview using JetPack Navigation [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I have an app that has MainActivity but all the work is in the fragment.
I made the fragment layout the HomePage using JetPack navigation. and it worked. but when i added the recycler view it crashed.
the error was this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.saheralsous.android, PID: 12418
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.saheralsous.android/com.saheralsous.android.MainActivity}: android.view.InflateException: Binary XML file line #20 in com.saheralsous.android:layout/activity_main: Binary XML file line #20 in com.saheralsous.android:layout/activity_main: Error inflating class fragment
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 #20 in com.saheralsous.android:layout/activity_main: Binary XML file line #20 in com.saheralsous.android:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #20 in com.saheralsous.android:layout/activity_main: Error inflating class fragment
Caused by: java.lang.NullPointerException: null cannot be cast to non-null type androidx.recyclerview.widget.RecyclerView
at com.saheralsous.android.PhotoGalleryFragment.onCreateView(PhotoGalleryFragment.kt:45)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:392)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
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.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
at com.saheralsous.android.MainActivity.onCreate(MainActivity.kt:9)
at android.app.Activity.performCreate(Activity.java:8000)
E/AndroidRuntime: 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)
I didn't add or change anything in the main activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
only in the activity_main i added the fragment for Navigation compnonent
<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">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
i initialize the recyclerview in the fragment this way:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
/**
* PagingDataAdapter
*/
RecyclerViewPhotoAdapter = RecyclerViewPhotoAdapter()
/**
* Recycler View
*/
PhotoRecyclerView =
view?.findViewById(R.id.recyclerview_main) as RecyclerView
PhotoRecyclerView.layoutManager = LinearLayoutManager(context)
//linking adapter with recyclerview
PhotoRecyclerView.adapter = RecyclerViewPhotoAdapter
/**
* Adapter, Repository and viewmodel
*/
pagingAdapter = PhotoPaging(
(requireActivity().application as MyApplication).networkApi
)
repository = GalleryFlowRepositoryImpl(pagingAdapter)
viewModel = ViewModelProvider(this, ViewModelProviderFactory(
PhotoGalleryViewModel::class
){
PhotoGalleryViewModel(repository)
}).get(PhotoGalleryViewModel::class.java)
//observing data
observers()
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_photo_gallery, container, false)
}
fragment_photo_gallery layout is simply this
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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=".PhotoGalleryFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</FrameLayout>
In your onCreateView you access the view before inflating the layout.
At line:
PhotoRecyclerView = view?.findViewById(R.id.recyclerview_main) as RecyclerView
you try to retrieve the recyclerview_main in the view wich is null because at this point the layout is not inflated.
Then you force cast it into a RecyclerView (as RecyclerView instead of as? RecyclerView for optional cast) wich lead to a NullPointerExcepion.
I would recommand moving your code into onViewCreated method.
ok it's not a big problem you need to inflate before you use view
first, add this on the top of your onCreateView
val view = inflater.inflate(R.layout.fragment_photo_gallery, container, false)
then return view at the end
return view
hope my answer helped you
I found problem in your code.
You didn't inflate view before use RecyclerView.
PhotoRecyclerView =
view?.findViewById(R.id.recyclerview_main) as RecyclerView
In there, view should be null. because you didn't inflate view.
So to resolve your problem, there are two methods.
First, in onCreateView method you should inflate view before using.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var view = inflater.inflate(R.layout.fragment_photo_gallery, container, false)
/**
* PagingDataAdapter
*/
RecyclerViewPhotoAdapter = RecyclerViewPhotoAdapter()
/**
* Recycler View
*/
PhotoRecyclerView =
view?.findViewById(R.id.recyclerview_main) as RecyclerView
PhotoRecyclerView.layoutManager = LinearLayoutManager(context)
//linking adapter with recyclerview
PhotoRecyclerView.adapter = RecyclerViewPhotoAdapter
/**
* Adapter, Repository and viewmodel
*/
pagingAdapter = PhotoPaging(
(requireActivity().application as MyApplication).networkApi
)
repository = GalleryFlowRepositoryImpl(pagingAdapter)
viewModel = ViewModelProvider(this, ViewModelProviderFactory(
PhotoGalleryViewModel::class
){
PhotoGalleryViewModel(repository)
}).get(PhotoGalleryViewModel::class.java)
//observing data
observers()
// Inflate the layout for this fragment
return view
}
Or Second, you can use your code in onViewCreated method.

In this news app, I keep getting InflateException

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.newsapp/com.example.newsapp.ui.MainActivity}:
android.view.InflateException: Binary XML file line #25 in
com.example.newsapp:layout/activity_main: Binary XML file line #25 in
com.example.newsapp:layout/activity_main: Error inflating class
fragment
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)
class MainActivity : AppCompatActivity() {
lateinit var viewModel : NewsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val newsRepository = NewsRepository(ArticleDatabase(this))
val viewModelProviderFactory = NewsViewModelProviderFactory(newsRepository)
viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
bottomNavigationView.setupWithNavController(nav_host_fragment_container.findNavController())
}
<FrameLayout
android:id="#+id/flFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<fragment
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nav_host_fragment_container"
app:defaultNavHost="true"
app:navGraph="#navigation/news_nav_graph"/>
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="56dp"
app:backgroundTint="#color/grey"
app:menu="#menu/bottom_navigation_menu"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"/>
You have two mistakes in the code
First, you name the listview and the listfiles with the same variable name
// look at that in these lines, both of them had the same variable name
private lateinit var list: ListView
val list = dir.listFiles()
Second, the part which makes the exception in this line
val list = dir.listFiles() // dir.listFiles() returns null
check this answer if you want to get a list of files in directory as I understand

Google maps fragment in epoxy view

I'm currently exploring the new MvRx stack from Airbnb
Rigth now i am adding a google maps fragment successfully to a BaseMvRxFragment in a BottomNavigationView.
The problem is that the 2. time i navigate to the MapFragment my app crashes and i get the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: getflareapp.com.s2s, PID: 19184
android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f080093, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3752)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:405)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:387)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.view.View.inflate(View.java:23239)
at getflareapp.com.s2s.views.MapView.<init>(MapView.kt:19)
at getflareapp.com.s2s.views.MapView.<init>(MapView.kt:14)
at getflareapp.com.s2s.views.MapView.<init>(Unknown Source:6)
at getflareapp.com.s2s.views.MapViewModel_.buildView(MapViewModel_.java:42)
at getflareapp.com.s2s.views.MapViewModel_.buildView(MapViewModel_.java:22)
MapFragment.kt
/**
* A simple [BaseFragment] subclass.
*
*/
class MapFragment : BaseFragment() {
private val mViewModel: ChatViewModel by fragmentViewModel()
override fun epoxyController() = simpleController(mViewModel) {state ->
mapView{
id("map")
}
}
}
MapView.kt
#ModelView(autoLayout = ModelView.Size.MATCH_WIDTH_MATCH_HEIGHT)
class MapView #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
init {
// TODO: Fix crash on second view.
inflate(context, R.layout.view_map, this)
}
}
view_map.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map2"
android:name="getflareapp.com.s2s.ui.map.MapFragment"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity" />
</FrameLayout>
Thanks for any help! <3
I´ve problems adding directly the map fragment inner other fragment, so i suggest change that with Framelayout and inflate the fragment manually.

Categories

Resources