Android – Toast.makeText from resource string

androidandroid-resourcestoast

I have a class named MyPrimaryClass, this class has a button witch when pressed, creates an Intent with the class myClassForResult.

I use this to start it:

startActivityForResult(myIntentOfMyClassForResult, ACTIVITY_EDIT_BTEXT);

Both MyPrimaryClass, and myClassForResult extends Activity.

So, when I call Toast.makeText within the myClassForResult, with the text parameter of R.string.my_resource_string, it gives me Force Close!

I have tried this:

Context c = myClassForResult.this;
Toast toast = Toast.makeText(c,
    c.getResources().getString(R.string.my_resource_string),
    Toast.LENGTH_SHORT);
toast.show();

Also this: c = getApplicationContext()

Also this: c = getBaseContext()

Also this:

Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
    R.string.my_resource_string,
    Toast.LENGTH_SHORT);
toast.show();

If I use an inline string, like "My toast Text!", it works. But i need to get a string from the resources.

-Problem solved:

To solve the problem I changed the duration of the Toast to Toast.LENGTH_LONG

The string R.string.my_resource_string value is "The title is empty"

When I change its value to "The title", it worked properly, so I guess the string was too long for the Toast.LENGTH_SHORT duration.

But when i change the duration to Toast.LENGTH_LONG, I could use the long string.

Context c = MyPrimaryClass.this;
Toast toast = Toast.makeText(c,
    R.string.my_resource_string,
    Toast.LENGTH_LONG);
toast.show();

Best Answer

Try:

Toast.makeText(this, this.getString(R.string.my_resource_string), Toast.LENGTH_SHORT);