Anko toast() method causes java.lang.NoSuchMethodError when called from Fragment
Asked Answered
S

2

9

I'm having following error when I'm calling toast("Toast's message text") from Android Fragment:

java.lang.NoSuchMethodError: No virtual method getActivity()Landroid/app/Activity; in class Landroid/support/v4/app/Fragment; or its super classes (declaration of 'android.support.v4.app.Fragment' appears in name-of-the-file-classes.dex)

I'm using Anko v0.9.1 and Kotlin 1.0.6

What might be the cause of this crash? Standard Android Toast works just fine. Also toast() function works inside Activities.

Subglacial answered 30/1, 2017 at 9:12 Comment(8)
use this Toast.makeText(getActivity(),"message",Toast.LENGTH_SHORT).show();Robb
I stated in my questions that standard Android Toast works without problems. But I would like to know why Anko's "toast()" extension method doesn't work in this case.Subglacial
what is your implementation of toast() methodRobb
It is not my implementation, it's Anko: github.com/Kotlin/ankoSubglacial
Post your code.Arin
toast("text") in fragment's button onClickListener :) (normal Toast works in the same place)Subglacial
File a bug on anko Github and use standard Toast API for now.Vegetable
@JanSlominski, I have the same error and have created issue github.com/Kotlin/anko/issues/328Futtock
F
11

It is very strange, probably it is a bug.

But next works for me

activity.toast("Toast's message text")

or

context.toast("Toast's message text")
Futtock answered 24/2, 2017 at 7:15 Comment(1)
Took me embarrassingly long to figure out I was calling this from a fragment and needed context/activityWardlaw
U
1

If you want to use it inside a class (an adapter, for example), surely you have to get the activity first (context)

holder.itemView.setOnClickListener(
                { view ->
                    view.getContext().toast("Message")
                }
        )
Unicellular answered 1/5, 2018 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.