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;
}
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?

add a comment |
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?

context
is null, just make sure to set a value before casting it toMainActivity
– Omar Mainegra
Jan 2 at 16:55
It is aTypecast Exception
and it is sayingcan 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
add a comment |
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?

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?


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 toMainActivity
– Omar Mainegra
Jan 2 at 16:55
It is aTypecast Exception
and it is sayingcan 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
add a comment |
context
is null, just make sure to set a value before casting it toMainActivity
– Omar Mainegra
Jan 2 at 16:55
It is aTypecast Exception
and it is sayingcan 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
add a comment |
3 Answers
3
active
oldest
votes
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()
}
add a comment |
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.
add a comment |
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)!!
}
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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()
}
add a comment |
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()
}
add a comment |
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()
}
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()
}
answered Jan 2 at 17:26


kcoppockkcoppock
114k39226245
114k39226245
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Jan 3 at 9:33


Ehsan MashhadiEhsan Mashhadi
783619
783619
add a comment |
add a comment |
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)!!
}
}
add a comment |
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)!!
}
}
add a comment |
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)!!
}
}
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)!!
}
}
answered Jan 3 at 9:57


SinaMN75SinaMN75
282411
282411
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
context
is null, just make sure to set a value before casting it toMainActivity
– Omar Mainegra
Jan 2 at 16:55
It is a
Typecast Exception
and it is sayingcan 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