0

So I'm fairly new to Kotlin.

I am trying to create an onClickListener on an image button to open the share interface, so that the particular video from the recyclerView can be shared via SMS, etc.

I followed various tutorials on how to do this as I am trying to execute this within a fragment, and the app just keeps crashing when I try to open the fragment in question.

I get the following error

java.lang.ClassCastException: java.lang.Integer cannot be cast to android.widget.ImageButton

Here is what my fragment code looks like:

SearchFragment.kt

class SearchFragment : Fragment(), View.OnClickListener
{

    private var layoutManager: RecyclerView.LayoutManager? = null
    private var adapter: RecyclerView.Adapter<ClipAdapter.ViewHolder>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View
    {
        val rootView = inflater.inflate(R.layout.fragment_search, container, false)
        loadData()
        return rootView
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        val shareBtn = view.findViewById<ImageButton>(R.id.button_to_share)
        shareBtn.setOnClickListener(this)
    }

    private fun loadData()
    {
        val service = TwitchServiceBuilder.buildService(TwitchService::class.java)
        val requestCall = service.getClips("anerdfails")

        requestCall.enqueue(object : Callback<List<Clip>>
        {
            override fun onResponse(
                call: Call<List<Clip>>,
                response: Response<List<Clip>>
            )
            {
                if (response.isSuccessful)
                {
                    //process data
                    recyclerView.layoutManager = GridLayoutManager(activity, 2)
                    recyclerView.adapter = ClipAdapter(response.body()!!)
                } else
                {
                    //output alert
                    AlertDialog.Builder(activity!!)
                        .setTitle("API error")
                        .setMessage("Response, but something went wrong ${response.message()}")
                        .setPositiveButton(android.R.string.ok) { _, _ -> }
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show()
                }
            }

            override fun onFailure(call: Call<List<Clip>>, t: Throwable)
            {
                //process failure
                AlertDialog.Builder(activity!!)
                    .setTitle("API error")
                    .setMessage("No response, and something went wrong $t")
                    .setPositiveButton(android.R.string.ok) { _, _ -> }
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show()
            }
        })
    }

    override fun onClick(v: View?)
    {
        Toast.makeText(activity, "Its toast!", Toast.LENGTH_SHORT).show()
    }

}

And here are my 2 layouts for the RecyclerView:

fragment_search.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"
    android:paddingStart="15dp"
    android:paddingTop="?attr/actionBarSize"
    android:paddingEnd="15dp"
    tools:context=".ui.search.SearchFragment">

    <androidx.appcompat.widget.SearchView
        android:background="@drawable/search_bar"
        android:id="@+id/clipSearch"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="5dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        app:layout_constraintBottom_toTopOf="@+id/recyclerView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="75dp"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/clipSearch" />

</androidx.constraintlayout.widget.ConstraintLayout>

clip_layout.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="wrap_content"
    tools:context=".ui.search.SearchFragment">

    <VideoView
        android:id="@+id/videoClip"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintDimensionRatio="w,2:3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/videoClip"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtChannel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtTitle"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtGame"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtChannel"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtViews"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtGame"
        tools:ignore="HardcodedText" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal"
        android:weightSum="2"
        android:layout_marginTop="15dp"
        app:layout_constraintTop_toBottomOf="@+id/txtViews">

        <ImageButton
            android:id="@+id/favouriteButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_baseline_favorite_border_24" />

        <ImageButton
            android:id="@+id/button_to_share"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_baseline_share_24" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Seems like a simple mistake on my part, but I'm pulling my hair out trying to work out what I've done wrong to cause the error on loading.

Any help would be appreciated.

0

2 Answers 2

2

I see you're trying to find the button "ShareBtn" inside the fragment which is totally wrong. the "ShareBtn" doesn't belong to the fragment, it belongs to the viewHolder which you have created inside "ClipAdapter" What you need to do is creating an interface inside "ClipAdapter" and create an object from it inside the Adapter then call the method which is should the clickListener delegates the click to it lastly, you should implement it inside the fragment and put whatever logic you want This link will help you implement it

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

2 Comments

Absolute legend, added the onClickListener to the ViewHolder class in my Adapter and the toast message is coming up as intended.
I'm glad that i helped you, Your comment made my day
1

You are casting ID of view which is an Integer to ImageButton which is a View in this line

val shareBtn = R.id.button_to_share as ImageButton

You should use this instead

val shareBtn = findViewById<ImageButton>(R.id.button_to_share)

UPDATE

Also you should find views after fragment view got created. It means you should call `findViewById` inside `onViewCreated` and not inside `onCreateView`. If you try to find views before view of fragment gets created then you get `NullPointerException` since there is no view yet.

3 Comments

Brill, so that fixed the initial error I was getting. I am now getting an new error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference - a brief Google suggested this could be due to the fact it's in the inner layout file, instead of the one which is being invoked on the onCreateView() method. How would I go about resolving it? I've updated the question with the layout code too.
@E.Fitzpatrick I have updated my answer. See if it solves your issue or not :D
I tried what you suggested and moved the click listener onto the onViewCreated() function (see original question for updated code), and I'm still getting the same error. Logcat specified that the error is from this line: shareBtn.setOnClickListener(this)

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.