Search code examples
javaandroidhard-coding

Avoid hardcoding messages in java classes


Here's a sample code:

toastMessage = "Data added successfully";
...  
Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show();

In this way, users only can interact with the English language, What can I do, if I wanted to show messages like above to user base on their language preferences (e.g. German or France) in android.

Thanks.


Solution

  • You can use strings from string.xml (and all other resources) in the code.

    Toast.makeText(this, R.string.string_id, Toast.LENGTH_SHORT).show();
    

    or for other places where you can't use id directly:

    context.getString(R.string.string_id)