Barry
Barry

Reputation: 1258

using a string resource in a Toast

My code is:

public static void ToastMemoryShort (Context context) {
    CharSequence text = getString(R.string.toast_memoryshort); //error here
    Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    return;
    }

but I'm getting "Cannot make a static reference to the non-static method getString(int) from the type Context" in Eclipse. I'm trying to get ready for localising my app (getting all the hard coded strings into resources), so where I have:

getString(R.string.toast_memoryshort)

I previously had a hard coded string which was fine.

I'm not sure what's going on here (Java noob). Can anyone enlighten me please?

Many thanks

Baz

Upvotes: 16

Views: 35989

Answers (5)

Prajwal Waingankar
Prajwal Waingankar

Reputation: 2718

Use the below code to get the desired output:

Toast.makeText(getApplicationContext(),getString(R.string.exit_survey_toast),Toast.LENGTH_LONG).show();

replace exit_survey_toast with your string value.

Upvotes: 2

You could make your toast more generic like this:

public void toast(String msg){
    Context context = getApplicationContext();
    CharSequence text = msg;
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

Then just call when you need like this:

toast( "My message hardcoded" );

or by referring to strings.xml like this:

toast( this.getString(R.string.toast_memoryshort) );

Upvotes: 2

JoseF
JoseF

Reputation: 1311

You should change

CharSequence text = getString(R.string.toast_memoryshort); //error here

for:

CharSequence text = context.getString(R.string.toast_memoryshort);

The getString function is implemented in Context#getString(int)

Upvotes: 0

Rasel
Rasel

Reputation: 15477

Change to

 public static void ToastMemoryShort (Context context) {

        Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
        return;
        }

Upvotes: 29

Stefan H Singer
Stefan H Singer

Reputation: 5504

Just use this instead:

makeText(Context context, int resId, int duration) Make a standard toast that just contains a text view with the text from a resource.

From http://developer.android.com/reference/android/widget/Toast.html

Upvotes: 7

Related Questions