user531100
user531100

Reputation: 3

How to create a Toast from a class

I have a new project - MyProject. In that project I have the class MyProject and another class uTorrent. How do I show a toast from the uTorrent class? When I try this:

Toast toast = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);

I get this error:

The method getApplicationContext() is undefined for the type uTorrent

Thanks

Upvotes: 0

Views: 7242

Answers (5)

Dam
Dam

Reputation: 231

What you can do is make a public function in you activity like this :

in Activity.Class :

public void makeToast(String message) {
    Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
}

then call from uTorrent.class :

activity.makeToast(e.getMessage());

But it suppose you gave the activity as a parameter to uTorrent.

Upvotes: 1

JesusS
JesusS

Reputation: 1665

Try to give the class a Context variable with the context where you want to show the Toast.

Anyway i guess that djg have the correct answer

Upvotes: 0

Waleed
Waleed

Reputation: 21

The post seems to be old, but I'm posting this answer in case someone is having the same issue

Answer:

You need to extend the class, as follows:

package HelloAndroid.workspace;

import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

public class myClass **extends Activity**{

......

}

Upvotes: 2

Ryan Reeves
Ryan Reeves

Reputation: 10249

You need to pass a Context into the class you're using the Toast.

Upvotes: 1

djg
djg

Reputation: 1283

Are you calling this from an Activity? It would help to see some code, but what you need is a Context. This will typically be your Activity or Application class.

Upvotes: 0

Related Questions