use of string resource in 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 get "Can't make a static reference to the non-static getString (int) method from type Context" in Eclipse. I am trying to prepare for the localization of my application (getting all hardcoded strings into resources), so I have:

 getString(R.string.toast_memoryshort) 

I previously had a hard-coded string that was fine.

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

Many thanks

Baz

+10
source share
5 answers

Just use this instead:

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

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

+4
source

Change to

  public static void ToastMemoryShort (Context context) { Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show(); return; } 
+21
source

You can make your toast more general:

 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 with a link to strings.xml, like this:

 toast( this.getString(R.string.toast_memoryshort) ); 
+2
source

You have to change

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

for

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

getString function implemented in Context # getString (int)

0
source

Use the code below to get the desired result:

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

replace exit_survey_toast with your string value.

0
source

All Articles