Kotlin: How to call getSupportFragmentManager() in RecyclerView.Adapter





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-1















I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:



(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
.commit()


But I get the following error:




kotlin.TypeCastException: null cannot be cast to non-null type




Can you help me?










share|improve this question

























  • context is null, just make sure to set a value before casting it to MainActivity

    – Omar Mainegra
    Jan 2 at 16:55











  • It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

    – Murtaza Khursheed Hussain
    Jan 3 at 9:36


















-1















I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:



(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
.commit()


But I get the following error:




kotlin.TypeCastException: null cannot be cast to non-null type




Can you help me?










share|improve this question

























  • context is null, just make sure to set a value before casting it to MainActivity

    – Omar Mainegra
    Jan 2 at 16:55











  • It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

    – Murtaza Khursheed Hussain
    Jan 3 at 9:36














-1












-1








-1








I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:



(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
.commit()


But I get the following error:




kotlin.TypeCastException: null cannot be cast to non-null type




Can you help me?










share|improve this question
















I would like to call the Support Fragment Manager in my RecyclerView.Adapter after the click event in order to move to a different fragment. My approach:



(context as MainActivity).supportFragmentManager
.beginTransaction()
.replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
.commit()


But I get the following error:




kotlin.TypeCastException: null cannot be cast to non-null type




Can you help me?







android kotlin






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 9:29









Lovis

4,44522140




4,44522140










asked Jan 2 at 16:21









Simon GiesenSimon Giesen

195




195













  • context is null, just make sure to set a value before casting it to MainActivity

    – Omar Mainegra
    Jan 2 at 16:55











  • It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

    – Murtaza Khursheed Hussain
    Jan 3 at 9:36



















  • context is null, just make sure to set a value before casting it to MainActivity

    – Omar Mainegra
    Jan 2 at 16:55











  • It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

    – Murtaza Khursheed Hussain
    Jan 3 at 9:36

















context is null, just make sure to set a value before casting it to MainActivity

– Omar Mainegra
Jan 2 at 16:55





context is null, just make sure to set a value before casting it to MainActivity

– Omar Mainegra
Jan 2 at 16:55













It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

– Murtaza Khursheed Hussain
Jan 3 at 9:36





It is a Typecast Exception and it is saying can not be cast to non-null type something which does not allow null you are passing null to it. In Kotlin you need to add ? to make in nullable

– Murtaza Khursheed Hussain
Jan 3 at 9:36












3 Answers
3






active

oldest

votes


















0














This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.



Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:



class MyAdapter : RecyclerView.Adapter<MyType> {
private var listener: (() -> Unit)? = null

fun setListener(listener: (() -> Unit)?) {
this.listener = listener
}

// wherever your onClick is handled:
listener?.invoke()
}


Then, in the Activity that's initializing MyAdapter:



myAdapter.setListener {
supportFragmentManager
.beginTransaction()
.replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
.commit()
}





share|improve this answer































    0














    I suggest you handle your fragment transaction in your fragment/activity. This would help you to have cleaner code and using context in fragment/activity is much easier. Try to define the interface between your adapter and fragment and call your interface method in the adapter and implement the interface in activity/fragment. There you can access context easily.






    share|improve this answer































      0














      get the activity or fragment as argument in your adapter.



      class ArticleAdapter(private val articleActivity: ArticleActivity, private val docs: List<ArticleResult.ArticleDoc>) : RecyclerView.Adapter<ArticleAdapter.Holder>() {
      override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder = Holder(LayoutInflater.from(p0.context).inflate(R.layout.row_general2, p0, false))
      override fun getItemCount(): Int = docs.size

      override fun onBindViewHolder(holder: Holder, position: Int) {
      articleActivity.supportFragmentManager
      }

      class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
      val textViewTitleRow = itemView.findViewById<TextView>(R.id.textViewTitleRow)!!
      val textView1Row = itemView.findViewById<TextView>(R.id.textView1Row)!!
      val textView2Row = itemView.findViewById<TextView>(R.id.textView2Row)!!
      val imageViewDownloadRow = itemView.findViewById<ImageView>(R.id.imageViewDownloadRow)!!
      val textViewMoreRow = itemView.findViewById<TextView>(R.id.textViewMoreRow)!!
      val imageViewBookRow = itemView.findViewById<ImageView>(R.id.imageViewBookRow)!!
      }
      }





      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009730%2fkotlin-how-to-call-getsupportfragmentmanager-in-recyclerview-adapter%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.



        Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:



        class MyAdapter : RecyclerView.Adapter<MyType> {
        private var listener: (() -> Unit)? = null

        fun setListener(listener: (() -> Unit)?) {
        this.listener = listener
        }

        // wherever your onClick is handled:
        listener?.invoke()
        }


        Then, in the Activity that's initializing MyAdapter:



        myAdapter.setListener {
        supportFragmentManager
        .beginTransaction()
        .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
        .commit()
        }





        share|improve this answer




























          0














          This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.



          Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:



          class MyAdapter : RecyclerView.Adapter<MyType> {
          private var listener: (() -> Unit)? = null

          fun setListener(listener: (() -> Unit)?) {
          this.listener = listener
          }

          // wherever your onClick is handled:
          listener?.invoke()
          }


          Then, in the Activity that's initializing MyAdapter:



          myAdapter.setListener {
          supportFragmentManager
          .beginTransaction()
          .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
          .commit()
          }





          share|improve this answer


























            0












            0








            0







            This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.



            Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:



            class MyAdapter : RecyclerView.Adapter<MyType> {
            private var listener: (() -> Unit)? = null

            fun setListener(listener: (() -> Unit)?) {
            this.listener = listener
            }

            // wherever your onClick is handled:
            listener?.invoke()
            }


            Then, in the Activity that's initializing MyAdapter:



            myAdapter.setListener {
            supportFragmentManager
            .beginTransaction()
            .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
            .commit()
            }





            share|improve this answer













            This is because your Context instance in the adapter is not guaranteed to be an Activity. It could potentially be a ContextWrapper holding the Activity as a base Context. Attempting to unwrap this would be fragile.



            Instead, I would recommend that you define an interface in your adapter. From your Activity, provide an implementation of this interface to your adapter that will perform the FragmentTransaction. For example:



            class MyAdapter : RecyclerView.Adapter<MyType> {
            private var listener: (() -> Unit)? = null

            fun setListener(listener: (() -> Unit)?) {
            this.listener = listener
            }

            // wherever your onClick is handled:
            listener?.invoke()
            }


            Then, in the Activity that's initializing MyAdapter:



            myAdapter.setListener {
            supportFragmentManager
            .beginTransaction()
            .replace(MainActivity.FRAGMENT_CONTAINER, TextScreen())
            .commit()
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 2 at 17:26









            kcoppockkcoppock

            114k39226245




            114k39226245

























                0














                I suggest you handle your fragment transaction in your fragment/activity. This would help you to have cleaner code and using context in fragment/activity is much easier. Try to define the interface between your adapter and fragment and call your interface method in the adapter and implement the interface in activity/fragment. There you can access context easily.






                share|improve this answer




























                  0














                  I suggest you handle your fragment transaction in your fragment/activity. This would help you to have cleaner code and using context in fragment/activity is much easier. Try to define the interface between your adapter and fragment and call your interface method in the adapter and implement the interface in activity/fragment. There you can access context easily.






                  share|improve this answer


























                    0












                    0








                    0







                    I suggest you handle your fragment transaction in your fragment/activity. This would help you to have cleaner code and using context in fragment/activity is much easier. Try to define the interface between your adapter and fragment and call your interface method in the adapter and implement the interface in activity/fragment. There you can access context easily.






                    share|improve this answer













                    I suggest you handle your fragment transaction in your fragment/activity. This would help you to have cleaner code and using context in fragment/activity is much easier. Try to define the interface between your adapter and fragment and call your interface method in the adapter and implement the interface in activity/fragment. There you can access context easily.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 3 at 9:33









                    Ehsan MashhadiEhsan Mashhadi

                    783619




                    783619























                        0














                        get the activity or fragment as argument in your adapter.



                        class ArticleAdapter(private val articleActivity: ArticleActivity, private val docs: List<ArticleResult.ArticleDoc>) : RecyclerView.Adapter<ArticleAdapter.Holder>() {
                        override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder = Holder(LayoutInflater.from(p0.context).inflate(R.layout.row_general2, p0, false))
                        override fun getItemCount(): Int = docs.size

                        override fun onBindViewHolder(holder: Holder, position: Int) {
                        articleActivity.supportFragmentManager
                        }

                        class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                        val textViewTitleRow = itemView.findViewById<TextView>(R.id.textViewTitleRow)!!
                        val textView1Row = itemView.findViewById<TextView>(R.id.textView1Row)!!
                        val textView2Row = itemView.findViewById<TextView>(R.id.textView2Row)!!
                        val imageViewDownloadRow = itemView.findViewById<ImageView>(R.id.imageViewDownloadRow)!!
                        val textViewMoreRow = itemView.findViewById<TextView>(R.id.textViewMoreRow)!!
                        val imageViewBookRow = itemView.findViewById<ImageView>(R.id.imageViewBookRow)!!
                        }
                        }





                        share|improve this answer




























                          0














                          get the activity or fragment as argument in your adapter.



                          class ArticleAdapter(private val articleActivity: ArticleActivity, private val docs: List<ArticleResult.ArticleDoc>) : RecyclerView.Adapter<ArticleAdapter.Holder>() {
                          override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder = Holder(LayoutInflater.from(p0.context).inflate(R.layout.row_general2, p0, false))
                          override fun getItemCount(): Int = docs.size

                          override fun onBindViewHolder(holder: Holder, position: Int) {
                          articleActivity.supportFragmentManager
                          }

                          class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                          val textViewTitleRow = itemView.findViewById<TextView>(R.id.textViewTitleRow)!!
                          val textView1Row = itemView.findViewById<TextView>(R.id.textView1Row)!!
                          val textView2Row = itemView.findViewById<TextView>(R.id.textView2Row)!!
                          val imageViewDownloadRow = itemView.findViewById<ImageView>(R.id.imageViewDownloadRow)!!
                          val textViewMoreRow = itemView.findViewById<TextView>(R.id.textViewMoreRow)!!
                          val imageViewBookRow = itemView.findViewById<ImageView>(R.id.imageViewBookRow)!!
                          }
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            get the activity or fragment as argument in your adapter.



                            class ArticleAdapter(private val articleActivity: ArticleActivity, private val docs: List<ArticleResult.ArticleDoc>) : RecyclerView.Adapter<ArticleAdapter.Holder>() {
                            override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder = Holder(LayoutInflater.from(p0.context).inflate(R.layout.row_general2, p0, false))
                            override fun getItemCount(): Int = docs.size

                            override fun onBindViewHolder(holder: Holder, position: Int) {
                            articleActivity.supportFragmentManager
                            }

                            class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                            val textViewTitleRow = itemView.findViewById<TextView>(R.id.textViewTitleRow)!!
                            val textView1Row = itemView.findViewById<TextView>(R.id.textView1Row)!!
                            val textView2Row = itemView.findViewById<TextView>(R.id.textView2Row)!!
                            val imageViewDownloadRow = itemView.findViewById<ImageView>(R.id.imageViewDownloadRow)!!
                            val textViewMoreRow = itemView.findViewById<TextView>(R.id.textViewMoreRow)!!
                            val imageViewBookRow = itemView.findViewById<ImageView>(R.id.imageViewBookRow)!!
                            }
                            }





                            share|improve this answer













                            get the activity or fragment as argument in your adapter.



                            class ArticleAdapter(private val articleActivity: ArticleActivity, private val docs: List<ArticleResult.ArticleDoc>) : RecyclerView.Adapter<ArticleAdapter.Holder>() {
                            override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder = Holder(LayoutInflater.from(p0.context).inflate(R.layout.row_general2, p0, false))
                            override fun getItemCount(): Int = docs.size

                            override fun onBindViewHolder(holder: Holder, position: Int) {
                            articleActivity.supportFragmentManager
                            }

                            class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                            val textViewTitleRow = itemView.findViewById<TextView>(R.id.textViewTitleRow)!!
                            val textView1Row = itemView.findViewById<TextView>(R.id.textView1Row)!!
                            val textView2Row = itemView.findViewById<TextView>(R.id.textView2Row)!!
                            val imageViewDownloadRow = itemView.findViewById<ImageView>(R.id.imageViewDownloadRow)!!
                            val textViewMoreRow = itemView.findViewById<TextView>(R.id.textViewMoreRow)!!
                            val imageViewBookRow = itemView.findViewById<ImageView>(R.id.imageViewBookRow)!!
                            }
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 3 at 9:57









                            SinaMN75SinaMN75

                            282411




                            282411






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54009730%2fkotlin-how-to-call-getsupportfragmentmanager-in-recyclerview-adapter%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                MongoDB - Not Authorized To Execute Command

                                in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                Npm cannot find a required file even through it is in the searched directory