Not able to "findViewById" in Kotlin. Getting error "Type inference failed"

AndroidAndroid LayoutKotlinType Inference

Android Problem Overview


I am getting the following error when I try to find a RecycleView by id.

>Error:- >Type inference failed: Not enough information to infer parameter T

Error

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

Android Solutions


Solution 1 - Android

Try something like:

val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)

You can use Kotlin Android Extensions too for that. Check the doc here.
With it, you can call recycler_view directly in your code.

Kotlin Android Extensions:

  • In your app gradle.build add apply plugin: 'kotlin-android-extensions'
  • In your class add import for import kotlinx.android.synthetic.main.<layout>.* where <layout> is the filename of your layout.
  • That's it, you can call recycler_view directly in your code.

How does it work? The first time that you call recycler_view, a call to findViewById is done and cached.

Solution 2 - Android

You're on API level 26, where the return type of findViewById is now a generic T instead of View and can therefore be inferred. You can see the relevant changelog here.

So you should be able to do this:

val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)

Or this:

val recycler_view: RecyclerView = findViewById(R.id.recycler_view)

Solution 3 - Android

DEPRECATED

In Kotlin we can get the id of the view without the use of the findViewById syntax.

For example we are using the following the layout from that we will get the id of the view and perform operation

>Layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/welcomeMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Hello World!"/>

</FrameLayout>

We are able to find the id of the view by using the following code

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
 
    welcomeMessage.text = "Hello Kotlin!" ////WE ARE GETTING THE IDS WITHOUT USING THE FINDVIEWBYID syntax
}

>HOW?

To be able to use it, you need an special import (the one I write below), but the IDE is able to auto-import it. Couldn’t be easier!

import kotlinx.android.synthetic.main.YOUR_LAYOUT_NAME.*/// HERE "YOUR_LAYOUT_NAME" IS YOUR LAYOUT NAME WHICH U HAVE INFLATED IN onCreate()/onCreateView() 

We need to import this property to get the id of the view without the use of the findviewbyid syntax.

For more information on this topic than please refer this link :- Click here

UPDATE

Now the kotlin-android-extensions is deprecated , instead of using the kotlin provided binding , we can use now the View-Binding and it works same as above solution, Just you need to use the below in your app gradle

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

Solution 4 - Android

Usually Kotlin can infer your type using the info provided in the brackets.

In this case, it can't so you would have to specify it explicitly like this

findViewById<RecyclerView>(R.id.recycler_view)

Not really sure about the type though but that is how you should specify it

I'd like to add that, using Anko, you can further simplify your code like this:

val recycler_view : RecyclerView =  find(R.id.recycler_view)

Solution 5 - Android

Add this line for your code as Whatever you are using controller.

val tvHello = findViewById<TextView>(R.id.tvHello)

Solution 6 - Android

You can ignore giving ids to variables in kotlin. You just need to use a plugin

Paste this in your gradle

 apply plugin: 'kotlin-android-extensions'

and then you don't need to assign ids to var, you can just do it like

 recycler_view.setAdapter(youradapter);

Solution 7 - Android

Was unable to access the ui components like OP faced looks like below was needed inside app gradle:

plugins {
    ...
    id 'kotlin-android-extensions'
}

Even though after adding this line android studio was still not able to auto resolve the imports for kotlin synthetics so you may need to invalidate cache and restart.

If still not working then import manually depending on views

  • activity /fragment view: import kotlinx.android.synthetic.main..*
  • normal views : import kotlinx.android.synthetic.main..view.*

Update - 2

If you are getting this info warning -

> Warning: The 'kotlin-android-extensions' Gradle plugin is deprecated.

plugin 'kotlin-android-extensions' is going to be deprecated. So add below in your app gradle

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

Solution 8 - Android

Try this:

Here bind generic function use to bind view. its general function it's can use for any view.

class MyActivity : AppCompatActivity() {
    private lateinit var recycler_view : RecyclerView
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        recycler_view = bind(R.id.recycler_view)
    }
}

fun <T : View> Activity.bind(@IdRes res : Int) : T {
    @Suppress("UNCHECKED_CAST")    
    return findViewById(res) as T
}

Solution 9 - Android

You don't even have to create an object to do things with a view. You can just use the id. For example, Kotlin

recycle_view.adapter = adapter

is same as, Java

RecycleView recycle_view = (RecycleView) findViewById(recycle_view);
recycle_view.setAdapter(adapter);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRavindra KushwahaView Question on Stackoverflow
Solution 1 - AndroidKevin RobatelView Answer on Stackoverflow
Solution 2 - Androidzsmb13View Answer on Stackoverflow
Solution 3 - AndroidRavindra KushwahaView Answer on Stackoverflow
Solution 4 - AndroidAlf MohView Answer on Stackoverflow
Solution 5 - AndroidNajib.NjView Answer on Stackoverflow
Solution 6 - AndroidAnmol317View Answer on Stackoverflow
Solution 7 - AndroidMDTView Answer on Stackoverflow
Solution 8 - AndroidMehul KabariaView Answer on Stackoverflow
Solution 9 - AndroidAjay SivanView Answer on Stackoverflow