0

I know this has been asked many times but i am really not able to understand why I am not able to add Floating Action Button in one of the fragments of TabLayout.

It is giving me error as 'kotlin.TypeCastException: null cannot be cast to non-null type android.support.design.widget.FloatingActionButton' in my logcat.

I am new to android and app development and really appreciate help here as I have already wasted my 3 days

MainActivity Code:

class MainActivity : AppCompatActivity() {


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val fab = findViewById<View>(R.id.fab) as FloatingActionButton

    fab.setOnClickListener { view ->
        Snackbar.make(view, "Replace with your own action",
                Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
    }
    initToolbar()


    val tabLayout: TabLayout = findViewById(R.id.tab_layout)

    val viewPager: ViewPager = findViewById(R.id.view_pager)

    val adapter = SampleAdapter(supportFragmentManager)


    viewPager.adapter = adapter



    tabLayout.setupWithViewPager(viewPager)

    tabLayout.addOnTabSelectedListener(object : 
 TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab) {

        }

        override fun onTabUnselected(tab: TabLayout.Tab) {

        }

        override fun onTabReselected(tab: TabLayout.Tab) {

        }
    })


    }

  private fun initToolbar() {
    val toolbar: Toolbar = findViewById(R.id.toolbar)
    setSupportActionBar(toolbar)
    supportActionBar!!.title = "Don't Forget"
  }
  }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:contentInsetStartWithNavigation="0dp"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        style="@style/CustomTabLayout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="left"
        android:background="@color/colorPrimary"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabTextAppearance="@style/TextAppearance.AppCompat" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

logcat:

  java.lang.RuntimeException: Unable to start activity 
  ComponentInfo{com.ashwinis.mylistapp/com.ashwinis.mylistapp.MainActivity}: 
  kotlin.TypeCastException: null cannot be cast to non-null type 
  android.support.design.widget.FloatingActionButton
 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: kotlin.TypeCastException: null cannot be cast to non-null type 
 android.support.design.widget.FloatingActionButton
 at com.ashwinis.mylistapp.MainActivity.onCreate(MainActivity.kt:25)
 at android.app.Activity.performCreate(Activity.java:6975)
 at 
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
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)  

fragment_one.xml

<LinearLayout 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:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="500dp"
    android:gravity="center_vertical|center_horizontal"
    android:text="FragmentOne" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="16dp"
    app:backgroundTint="@color/colorAccent"
    app:fabSize="mini"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:srcCompat="@android:drawable/ic_input_add" />

7
  • In your layout activity_main.xml is no item with the id fab, and you get a null pointer at val fab = findViewById<View>(R.id.fab) as FloatingActionButton because fab is null. Commented Jun 26, 2018 at 11:36
  • 1
    If you're new to android/kotlin, you might want to learn kotlin android extension plugin to get rid of findViewById calls. Commented Jun 26, 2018 at 11:45
  • @Pawel: Added your suggestion to OP in my answer. Commented Jun 26, 2018 at 11:50
  • Sorry..I missed to mention that I need to add Floating Action button to only one fragment 'fragment_one'. Adding 'fragment_one.xml' Commented Jun 26, 2018 at 11:54
  • @AshS Then you should bind the fragment_one.xml to your fragment class and instantiate the fab button and its function there. Commented Jun 26, 2018 at 13:10

1 Answer 1

4

You need to add a FloatingActionButton in your xml with id fab which is causing it to be null.

Also, when casting something that could be null to a type which is non-null (here FloatingActionButton) you need to use ?

Try

val fab = findViewById<View>(R.id.fab) as? FloatingActionButton

For more information read https://kotlinlang.org/docs/reference/typecasts.html#safe-nullable-cast-operator

EDIT

@Pawel's comment is really helpful. Read https://kotlinlang.org/docs/tutorials/android-plugin.html to get rid of findViewById calls which is the main reason of NPE.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.