Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 699
Jan Slominski Avatar asked Jan 30 '17 09:01

Jan Slominski


People also ask

How do you show a toast in fragment?

This is how you can show an Android Toast message from a Fragment: Toast. makeText(getActivity(), "Click!", Toast. LENGTH_SHORT).

What does toast do in Kotlin?

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.


2 Answers

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")
like image 141
Deni Erdyneev Avatar answered Sep 21 '22 20:09

Deni Erdyneev


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")
                }
        )
like image 37
Smaillns Avatar answered Sep 19 '22 20:09

Smaillns