16

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

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Barry
  • 1,258
  • 3
  • 13
  • 27

5 Answers5

28

Change to

 public static void ToastMemoryShort (Context context) {

        Toast.makeText(context, context.getString(R.string.toast_memoryshort), Toast.LENGTH_LONG).show();
        return;
        }
Rasel
  • 15,499
  • 6
  • 40
  • 50
  • The reason this answer is so much popular is that using `getString` in the first place suggests that string itself was needed for some reason (var injection, formatting etc.). Plus, it actually resolves the exception in question which is a genuine value. – tishma May 15 '17 at 09:11
6

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

Stefan H Singer
  • 5,469
  • 2
  • 25
  • 26
  • Actually, it was a combination of your answer and Rasel's: Needed the .show on the end, didn't need Rasel's ""+ before the resource ID: Toast.makeText(context, R.string.toast_memoryshort, Toast.LENGTH_LONG).show(); so +1 to Rasel too. Many thanks. – Barry Sep 07 '11 at 13:01
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) );
Dror
  • 5,107
  • 3
  • 27
  • 45
2

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.

Prajwal Waingankar
  • 2,534
  • 2
  • 13
  • 20
0

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)

JoseF
  • 1,261
  • 13
  • 30