question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ClassCast Exception when using custom view

See original GitHub issue

I am using a custom view to create imageSlider and I receive this error: android.widget.FrameLayout cannot be cast to PACKAGE_NAME.epoxy.CustomImageSlider

Here is my code: layout file: test_layout.xml

 <?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  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="wrap_content">

    <androidx.viewpager.widget.ViewPager
       android:id="@+id/view_pager_layout"
       android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_marginLeft="16dp"
      android:layout_marginRight="16dp"
      android:layout_gravity="start"
      app:tabIndicatorHeight="2dp"
       app:tabMode="scrollable" />
</FrameLayout>

Custom View class:

@ModelView(defaultLayout = R.layout.test_layout)
 class CustomImageSlider : FrameLayout {
    private var viewpager: ViewPager? = null

    private var sliderItems : List<AdapterSliderItemBindingModel_> = Collections.emptyList()

    constructor(context: Context) : super(context) {
    init()
}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    init()
}

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init()
}

private fun init() {
   val view = View.inflate(context, R.layout.test_layout, this)
   this.viewpager = view.findViewById(R.id.view_pager_layout)

}

fun bind(items: List<AdapterSliderItemBindingModel_>) {
    this.sliderItems = items
    this.viewpager?.adapter = MyPager()
}


 inner class MyPager : PagerAdapter() {
   
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val adapterProfileListItemBindingModel = sliderItems[position]

        return  adapterProfileListItemBindingModel.layout
    }

     override fun destroyItem(container: ViewGroup, position: Int, view: Any) {
        container.removeView(view as View)
    }

    override fun getCount(): Int {
        return sliderItems.size
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return `object` === view
       }

     }

}

Epoxy Model:

@EpoxyModelClass
abstract class EpoxyImageSliderModel : EpoxyModel<CustomImageSlider>() {
   var items: List<AdapterSliderItemBindingModel_>? = null

    override fun getDefaultLayout(): Int {
        return R.layout.test_layout
    }

    override fun bind(customImageSlider:CustomImageSlider) {
        super.bind(customImageSlider)
        customImageSlider.bind(items ?: ArrayList())
   }
}

Epoxy Controller (I have coded this class in java, as I couldn’t use @AutoModel in my controller class when I wrote it in kotlin, it threw AutoModel annotations must not be on private or static fields even though the field was public and non static)

 public class MyEpoxyController extends TypedEpoxyController {

   @AutoModel EpoxyImageSliderModel_ sliderModel;
    private long i = 0;

    @Override
     protected void buildModels(Object d) {
        List<BaseModel> data = (List<BaseModel>) d;
        for(BaseModel model: data){
            if(model != null && 
  model.getItem().component1().equals(SliderCollection.class.getSimpleName())) {
                sliderModel = new EpoxyImageSliderModel_();
                List<SliderItme> items = model.getSliderCollection().getSliderItme();
               List<AdapterSliderItemBindingModel_> temp = new ArrayList<>();
                for(SliderItme item: items){
                    AdapterSliderItemBindingModel_ m = new AdapterSliderItemBindingModel_();
                    m.sliderItem(item);
                    m.id(i++);
                    temp.add(m);
                }
                sliderModel.setItems(temp);
                sliderModel.id(i++);
                sliderModel.addTo(this);
            }
        }
    }
}

The AdapterSliderItemBindingModel_ epoxy model is generated from layout file with databinding, and I have used it in EpoxyImageSliderModel

I get this error : android.widget.FrameLayout cannot be cast to PACKAGE_NAME.epoxy.CustomImageSlider. I have checked similar issues and I used @AutoModel to generate ids for models, also I have set ids in controller before adding the model to controller but it didn’t help.

Here is the complete stack trace for error:

  java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to PACKAGE_NAME.epoxy.CustomImageSlider
    at PACKAGE_NAME.epoxy.EpoxyImageSliderModel_.handlePreBind(EpoxyImageSliderModel_.java:21)
    at com.airbnb.epoxy.EpoxyViewHolder.bind(EpoxyViewHolder.java:52)
    at com.airbnb.epoxy.BaseEpoxyAdapter.onBindViewHolder(BaseEpoxyAdapter.java:97)
    at com.airbnb.epoxy.EpoxyControllerAdapter.onBindViewHolder(EpoxyControllerAdapter.java:16)
    at com.airbnb.epoxy.BaseEpoxyAdapter.onBindViewHolder(BaseEpoxyAdapter.java:15)
    at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
    at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
    at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
    at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
    at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
    at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
    at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
    at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
    at android.view.View.layout(View.java:19590)PACKAGE_NAME
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at  
androidx.constraintlayout.widget.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1791)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1635)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1544)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
    at com.android.internal.policy.DecorView.onLayout(DecorView.java:758)
    at android.view.View.layout(View.java:19590)
    at android.view.ViewGroup.layout(ViewGroup.java:6053)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2484)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2200)
2019-05-28 23:32:56.526 23012-23012/E/AndroidRuntime:     at 
android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1386)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6733)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
    at android.view.Choreographer.doCallbacks(Choreographer.java:723)
    at android.view.Choreographer.doFrame(Choreographer.java:658)
    at 
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    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)

@elihart Can you please have a look and give some insight on this error?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
elihartcommented, Jun 10, 2019

FYI you can setup auto scrolling for a recyclerview pretty easy with something like this

class AutoScrollingController(private val target: Target) {
    private val automationHandler: Handler by lazy { Handler(Looper.getMainLooper()) }
    private var itemIndex: Int = 0
    var isRunning: Boolean = false
        private set
    var isCancelled: Boolean = false
        private set

    interface Target {
        /**
         * Scroll to the given position.
         * @return true if the scroll was successful, false if no more attempts should be made.
         */
        fun scrollToPosition(position: Int): Boolean
    }

    /**
     * Starts auto scrolling, if it hasn't already been started. Scrolling continues until it is canceled. Once [MAX_SCROLL_COUNT] images are
     * scrolled to this loops back to the first image and continues anew.
     */
    fun start() {
        if (isRunning || ANIMATIONS_DISABLED) {
            return
        }

        isCancelled = false
        isRunning = true

        automationHandler.postDelayed(object : Runnable {
            override fun run() {
                itemIndex++
                // Auto scrolling can be cancelled during the target callback
                if (target.scrollToPosition(itemIndex % MAX_SCROLL_COUNT) && !isCancelled) {
                    automationHandler.postDelayed(this, CYCLE_DELAY_MS)
                } else {
                    cancel()
                }
            }
        }, START_DELAY_MS)
    }

    fun cancel() {
        isCancelled = true
        isRunning = false
        automationHandler.removeCallbacksAndMessages(null)
    }
}
0reactions
vipulasricommented, Jul 23, 2019

@elihart How can I apply this AutoScrollingController to RecyclerView?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Android ClassCastException upon retrieving Custom View
I've just run into an issue when attempting to grab a custom View using findViewById(). The custom view otherwise displays and operates ...
Read more >
support.v7.preference.ListPreference throws a ... - Issue Tracker
ListPreference crashes with a ClassCastException each time it tries to populate a custom dialog layout set using android:dialogLayout (xml) or DialogPreference.
Read more >
java.lang.ClassCastException: com.sendbird.android.User ...
In UIkit, there is no screen moving from the member list screen to the operator list. It seems that you have customized it...
Read more >
Custom import processor throws ClassCastException
Hi , I have extended the MultiThreadedImportProcessor and and have overridden the processItemData_Impl as below public Item processItemData_Impl(final ...
Read more >
How to Fix java.lang.ClassCastException in TreeSet By Using ...
By providing a custom Comparator in TreeSet constructor. In wrapper class like Integer, Double, etc Comparator interface is already implemented, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found