18

I am new to Android and I am learning the SDK myself from resource available over the net.

I came across a situation now. I am trying the below code:

Type 1:getResources().getString(android.R.string.cancel);

Type 2: Resources.getSystem().getString(android.R.string.cancel);

Type 3: getString(android.R.string.cancel);

All of the above methods return the same value. So what are these methods, what are their use cases. What are the good practices on when to use which method. Please help me out.

Vivek Kalkur
  • 2,200
  • 2
  • 21
  • 40
Kannan Ramaswamy
  • 181
  • 1
  • 1
  • 3

3 Answers3

11

The difference is not only in what you get, but in WHERE can you use them.

The first and the third ones are using "context." invisibly. So, very often (in static members or out of activity members) you can't use them directly, unless you pass context or resource as a static variable or as a parameter into your scope. But the second one

Resources.getSystem().getString(android.R.string.cancel)

You can use ABSOLUTELY EVERYWHERE in your application, even in static constants declaration! But for system resources only

Gangnus
  • 24,044
  • 16
  • 90
  • 149
  • 7
    It comes with a downside though. `Resources.getSystem()` provides access to only system resources (no application resources), and is not configured for the current screen (can not use dimension units, does not change based on orientation, etc). – Alexander Suraphel Mar 14 '16 at 15:00
  • 1
    @AlexanderSuraphel Please, notice the last sentence of the answer. I absolutely agree with you. – Gangnus Mar 15 '16 at 07:46
4

All 3 return the same value, but Resources.getSystem() references to the system resources and might cause a crash if used incorrectly.

The advised usage is "getString(android.R.string.cancel);"

It is also used as such in the WalkieTalkieActivity.java code on the Android developer website.

Community
  • 1
  • 1
Lodorenos
  • 143
  • 1
  • 11
1

These three methods are all the same. Here is the root method : getApplicationContext().getResource().getString("") and here is shortcut method : getString("") Use the shortcut method when you are processing on apps context. In almost every case, we use getString() to get Strings defined in the String file.

eeerahul
  • 1,629
  • 4
  • 27
  • 38
Bulma
  • 990
  • 3
  • 16
  • 35