Issue
Does it matter whether I access strings from strings.xml file from different contexts?
I accessed it in many ways such as: getApplicationContext().getString(R.string.name)
, this.getString(R.string.name)
,MainActivity.this.getApplicationContext().getString(R.string.name)
, or simply getString(R.string.name)
.
I understand that the application context lasts the whole application lifetime, but I honestly do not know when I should use it. Also, I cannot understand what is the difference between using this
and MainActivity.this
.
Please explain how I should access strings from both activities and Java classes.
Solution
The key argument for using the Application Context or the Activity Context is the dependency to the lifecycle of the whole App or a component (Activity in this case). If you wanna access the strings.xml it doesn't really matter which of both you use. Because you just use the Context get a reference to the ressource, which goes away when the Activity will be destroyed. A more importent case would be if you pass the Context to another class f.e. Because then there is a dependency to this specific Context and can lead to memory leaks if you don't clean it. There is a nice explanation about this with the usage of a BroadcastReceiver in the docs.
There is no difference between this
and AnyClass.this
because it points to the same class object. But you have to use AnyClass.this
if you wanna access the outer class in an inner class. Or if you have an anonymous class and need to access fields of the outer class. You could see it as more strict because you refer to a specific class.
Answered By - Steve Benett
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.