Bilal Zamil
Bilal Zamil

Reputation: 25

What is the difference between the first code and the second code and why should I add getString?

first code with resources.getString

  btn_w.setOnClickListener {  Toast.makeText(this ,resources.getString(R.string.app_name) ,Toast.LENGTH_SHORT).show() }

second code without resources.getString

 btn_w.setOnClickListener {  Toast.makeText(this ,R.string.app_name ,Toast.LENGTH_SHORT).show() }

Upvotes: 1

Views: 39

Answers (2)

Sergey Glotov
Sergey Glotov

Reputation: 20346

There are two versions of makeText() methods, one accepts string resource ID and another accepts String itself. You don't have to add getString(). If you have string resource ID, you can call the corresponding method.

Toast.makeText(this, R.string.some_string_resource, Toast.LENGTH_SHORT).show()

There's no difference in functionality. In fact, the method accepting int calls the method accepting String inside.

public static Toast makeText(Context context, @StringRes int resId, @Duration int duration) throws Resources.NotFoundException {
    return makeText(context, context.getResources().getText(resId), duration);
}

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
    ...
}

Toast source code.

In case you don't know what is string resource then use the link from @JakeSteam answer :)

Upvotes: 2

Jake Lee
Jake Lee

Reputation: 7989

The first line of code looks up the appropriate string based on your resource ID (e.g. R.string.app_name's string resource may be "My App").

The second line of code just has your string's "resource ID". This ID is a number that can be used to look up the actual string (e.g. R.string.app_name's resource ID may be 1234567890).

The documentation on app resources, specifically resource IDs, maybe be useful.

Upvotes: 2

Related Questions