Tobi
Tobi

Reputation: 19

android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar even though that is not the case

Im not sure why i am getting this error. I am not casting from two different toolbars

Here is my code:

androidx.appcompat.widget.Toolbar toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.toolbar_header);
        setSupportActionBar(toolbar)

What am i doing wrong here.

Here is the error

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mycontactlist, PID: 12667
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mycontactlist/com.example.mycontactlist.ContactListActivity}: java.lang.ClassCastException: android.widget.Toolbar cannot be cast to androidx.appcompat.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)

Upvotes: 1

Views: 5025

Answers (2)

Rafsanjani
Rafsanjani

Reputation: 5453

In your XML, you probably declared your toolbar using just <Toolbar></Toolbar> in that case, the toolbar will be created from the package android.widget. So if you try to call findViewById by casting it to androidx.appcompat.widget.Toolbar it will surely throw you a RuntimeException.

If you are using AndroidX, which you should, then you have to change the xml declaration of your toolbar to <androidx.appcompat.widget.Toolbar></androidx.appcompat.widget.Toolbar>

You can then proceed to call your (androidx.appcompat.widget.Toolbar) findViewByid(..) which should succeed

Upvotes: 4

Mikhail
Mikhail

Reputation: 294

Wrong Toolbar class defined in your xml file. Change it from

<Toolbar .../>

to

<androidx.appcompat.widget.Toolbar .../>

Upvotes: 5

Related Questions