Using getResources() in non-activity class
up vote
101
down vote
favorite
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
Example:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
add a comment |
up vote
101
down vote
favorite
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
Example:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks. See my answer for a less risky solution.
– Jason Crosby
Aug 28 '13 at 18:34
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44
add a comment |
up vote
101
down vote
favorite
up vote
101
down vote
favorite
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
Example:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
Example:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
edited Jun 13 '15 at 21:34
Brian Tompsett - 汤莱恩
4,153133699
4,153133699
asked Oct 5 '11 at 19:26
ssk
3,7871567117
3,7871567117
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks. See my answer for a less risky solution.
– Jason Crosby
Aug 28 '13 at 18:34
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44
add a comment |
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks. See my answer for a less risky solution.
– Jason Crosby
Aug 28 '13 at 18:34
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44
It's normally not a good idea to pass around
Context objects in Android. It can lead to memory leaks. See my answer for a less risky solution.– Jason Crosby
Aug 28 '13 at 18:34
It's normally not a good idea to pass around
Context objects in Android. It can lead to memory leaks. See my answer for a less risky solution.– Jason Crosby
Aug 28 '13 at 18:34
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44
add a comment |
10 Answers
10
active
oldest
votes
up vote
124
down vote
accepted
You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context as a parameter
4
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks.
– Jason Crosby
Aug 28 '13 at 18:35
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.Contextobjects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying anActivityto a static object which needs aContextand said object isn't destroyed when theActivityis leads to theActivitypersisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.
– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
add a comment |
up vote
27
down vote
Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
add a comment |
up vote
8
down vote
There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.
Follow the steps to access getResources() in a non activity class without passing a context through the object.
- Create a subclass of
Application, for instancepublic class App extends Application {. Refer the code next to the steps. - Set the
android:nameattribute of your<application>tag in theAndroidManifest.xmlto point to your new class, e.g.android:name=".App"
- In the
onCreate()method of your app instance, save your context (e.g.this) to a static field namedappand create a static method that returns this field, e.g.getContext(). - Now you can use:
App.getContext()whenever you want to get a
context, and then we can useApp.getContext().getResources()to get values from the resources.
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
add a comment |
up vote
6
down vote
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
add a comment |
up vote
4
down vote
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
add a comment |
up vote
2
down vote
this can be done by using
context.getResources().getXml(R.xml.samplexml);
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
add a comment |
up vote
2
down vote
We can use context Context context = parent.getContext(); Where parent is the ViewGroup.
add a comment |
up vote
0
down vote
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
add a comment |
up vote
0
down vote
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
add a comment |
up vote
0
down vote
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
add a comment |
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
124
down vote
accepted
You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context as a parameter
4
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks.
– Jason Crosby
Aug 28 '13 at 18:35
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.Contextobjects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying anActivityto a static object which needs aContextand said object isn't destroyed when theActivityis leads to theActivitypersisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.
– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
add a comment |
up vote
124
down vote
accepted
You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context as a parameter
4
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks.
– Jason Crosby
Aug 28 '13 at 18:35
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.Contextobjects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying anActivityto a static object which needs aContextand said object isn't destroyed when theActivityis leads to theActivitypersisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.
– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
add a comment |
up vote
124
down vote
accepted
up vote
124
down vote
accepted
You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context as a parameter
You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context as a parameter
edited Mar 17 '15 at 13:14
surfer190
3,57875195
3,57875195
answered Oct 5 '11 at 19:29
LuckyLuke
18.3k65225383
18.3k65225383
4
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks.
– Jason Crosby
Aug 28 '13 at 18:35
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.Contextobjects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying anActivityto a static object which needs aContextand said object isn't destroyed when theActivityis leads to theActivitypersisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.
– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
add a comment |
4
It's normally not a good idea to pass aroundContextobjects in Android. It can lead to memory leaks.
– Jason Crosby
Aug 28 '13 at 18:35
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.Contextobjects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying anActivityto a static object which needs aContextand said object isn't destroyed when theActivityis leads to theActivitypersisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.
– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
4
4
It's normally not a good idea to pass around
Context objects in Android. It can lead to memory leaks.– Jason Crosby
Aug 28 '13 at 18:35
It's normally not a good idea to pass around
Context objects in Android. It can lead to memory leaks.– Jason Crosby
Aug 28 '13 at 18:35
17
17
As a basic rule of thumb sure, but I feel this is somewhat misleading.
Context objects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying an Activity to a static object which needs a Context and said object isn't destroyed when the Activity is leads to the Activity persisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.– Dororo
Feb 4 '14 at 9:09
As a basic rule of thumb sure, but I feel this is somewhat misleading.
Context objects are nasty because it is not immediately obvious if it is application-wide or activity-wide. Memory leaks (and crashes) occur when you supply the wrong one. For example, supplying an Activity to a static object which needs a Context and said object isn't destroyed when the Activity is leads to the Activity persisting after onDestroy, since it cannot be GCed due to this other static object. So yes, it can be dangerous, but knowing why it is dangerous I feel is important to mention here.– Dororo
Feb 4 '14 at 9:09
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
^Dororo, This is one of the most important comments I've ever read. Proper use of context is rarely if ever, discussed. I get the feeling I've had many an inexplicable bug because of it!
– Jon Dunn
Apr 13 at 13:06
add a comment |
up vote
27
down vote
Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
add a comment |
up vote
27
down vote
Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
add a comment |
up vote
27
down vote
up vote
27
down vote
Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.
Its not a good idea to pass Context objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity or Fragment, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context objects.
answered Aug 28 '13 at 18:33
Jason Crosby
1,99442036
1,99442036
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
add a comment |
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
This is good advice thanks. Would it be a problem in a SQLiteOpenHelper? In the constructor, you have to pass a context. It's no longer available in the other methods but I could store it in a private field.
– Peter
Oct 22 '13 at 5:31
2
2
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
@Peter Yes there are some classes that require you to pass in a context object. So its best to try to only use those classes like SqLiteOpenHelper in an activity or fragment so you don't have to pass around context object. If its unavoidable just make sure you set your reference to the context object to null when your done to help reduce the risk of memory leaks.
– Jason Crosby
Oct 22 '13 at 14:12
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
Passing context object isn't always bad, as long as you can monitor the activity's life cycle. If not then better use Application context instead of Activity context using getApplicationContext() to avoid memory leaks. See stackoverflow.com/questions/7144177/… for retrieving application context.
– FrozenFire
Jan 11 '16 at 3:21
add a comment |
up vote
8
down vote
There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.
Follow the steps to access getResources() in a non activity class without passing a context through the object.
- Create a subclass of
Application, for instancepublic class App extends Application {. Refer the code next to the steps. - Set the
android:nameattribute of your<application>tag in theAndroidManifest.xmlto point to your new class, e.g.android:name=".App"
- In the
onCreate()method of your app instance, save your context (e.g.this) to a static field namedappand create a static method that returns this field, e.g.getContext(). - Now you can use:
App.getContext()whenever you want to get a
context, and then we can useApp.getContext().getResources()to get values from the resources.
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
add a comment |
up vote
8
down vote
There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.
Follow the steps to access getResources() in a non activity class without passing a context through the object.
- Create a subclass of
Application, for instancepublic class App extends Application {. Refer the code next to the steps. - Set the
android:nameattribute of your<application>tag in theAndroidManifest.xmlto point to your new class, e.g.android:name=".App"
- In the
onCreate()method of your app instance, save your context (e.g.this) to a static field namedappand create a static method that returns this field, e.g.getContext(). - Now you can use:
App.getContext()whenever you want to get a
context, and then we can useApp.getContext().getResources()to get values from the resources.
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
add a comment |
up vote
8
down vote
up vote
8
down vote
There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.
Follow the steps to access getResources() in a non activity class without passing a context through the object.
- Create a subclass of
Application, for instancepublic class App extends Application {. Refer the code next to the steps. - Set the
android:nameattribute of your<application>tag in theAndroidManifest.xmlto point to your new class, e.g.android:name=".App"
- In the
onCreate()method of your app instance, save your context (e.g.this) to a static field namedappand create a static method that returns this field, e.g.getContext(). - Now you can use:
App.getContext()whenever you want to get a
context, and then we can useApp.getContext().getResources()to get values from the resources.
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
There is one more way without creating a object also. Check the reference. Thanks for @cristian. Below I add the steps which mentioned in the above reference. For me I don't like to create a object for that and access. So I tried to access the getResources() without creating a object. I found this post. So I thought to add it as a answer.
Follow the steps to access getResources() in a non activity class without passing a context through the object.
- Create a subclass of
Application, for instancepublic class App extends Application {. Refer the code next to the steps. - Set the
android:nameattribute of your<application>tag in theAndroidManifest.xmlto point to your new class, e.g.android:name=".App"
- In the
onCreate()method of your app instance, save your context (e.g.this) to a static field namedappand create a static method that returns this field, e.g.getContext(). - Now you can use:
App.getContext()whenever you want to get a
context, and then we can useApp.getContext().getResources()to get values from the resources.
This is how it should look:
public class App extends Application{
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
edited May 23 '17 at 12:25
Community♦
11
11
answered Sep 22 '15 at 20:05
Mahendran Sakkarai
5,35032756
5,35032756
add a comment |
add a comment |
up vote
6
down vote
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
add a comment |
up vote
6
down vote
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
add a comment |
up vote
6
down vote
up vote
6
down vote
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
answered Oct 5 '11 at 19:30
Kristian
3,42862328
3,42862328
add a comment |
add a comment |
up vote
4
down vote
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
add a comment |
up vote
4
down vote
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
add a comment |
up vote
4
down vote
up vote
4
down vote
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
answered May 4 '15 at 8:37
lizlalala
15110
15110
add a comment |
add a comment |
up vote
2
down vote
this can be done by using
context.getResources().getXml(R.xml.samplexml);
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
add a comment |
up vote
2
down vote
this can be done by using
context.getResources().getXml(R.xml.samplexml);
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
add a comment |
up vote
2
down vote
up vote
2
down vote
this can be done by using
context.getResources().getXml(R.xml.samplexml);
this can be done by using
context.getResources().getXml(R.xml.samplexml);
edited Jul 30 '12 at 11:10
Taryn♦
188k45285349
188k45285349
answered Jul 30 '12 at 9:38
A.R.Asha
571
571
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
add a comment |
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
Well, this did the Magic for me. Thanks @A.R.Asha
– Kenny Dabiri
Aug 15 '17 at 18:56
add a comment |
up vote
2
down vote
We can use context Context context = parent.getContext(); Where parent is the ViewGroup.
add a comment |
up vote
2
down vote
We can use context Context context = parent.getContext(); Where parent is the ViewGroup.
add a comment |
up vote
2
down vote
up vote
2
down vote
We can use context Context context = parent.getContext(); Where parent is the ViewGroup.
We can use context Context context = parent.getContext(); Where parent is the ViewGroup.
answered Dec 29 '16 at 15:52
Jaydip Umaretiya
351418
351418
add a comment |
add a comment |
up vote
0
down vote
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
add a comment |
up vote
0
down vote
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
add a comment |
up vote
0
down vote
up vote
0
down vote
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
edited Aug 28 '13 at 19:41
answered Aug 26 '13 at 18:41
Ankit Srivastava
1442623
1442623
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
add a comment |
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
2
2
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
I expect you were downvoted for assuming that there is a convenient 'ViewGroup parent' member variable. Rather stupid assumption.
– arnt
Dec 25 '13 at 21:27
add a comment |
up vote
0
down vote
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
add a comment |
up vote
0
down vote
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
add a comment |
up vote
0
down vote
up vote
0
down vote
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
This always works for me:
import android.app.Activity;
import android.content.Context;
public class yourClass {
Context ctx;
public yourClass (Handler handler, Context context) {
super(handler);
ctx = context;
}
//Use context (ctx) in your code like this:
XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
//OR
final Intent intent = new Intent(ctx, MainActivity.class);
//OR
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
//ETC...
}
Not related to this question but example using a Fragment to access system resources/activity like this:
public boolean onQueryTextChange(String newText) {
Activity activity = getActivity();
Context context = activity.getApplicationContext();
returnSomething(newText);
return false;
}
View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
itemsLayout.addView(customerInfo);
edited Feb 21 '15 at 12:49
answered Feb 21 '15 at 12:41
Elroy
199112
199112
add a comment |
add a comment |
up vote
0
down vote
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
add a comment |
up vote
0
down vote
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
add a comment |
up vote
0
down vote
up vote
0
down vote
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
In the tour guide app of Udacity's Basic ANdroid course I have used the concept of Fragments. I got stuck for a while experiencing difficulty to access some string resources described in strings, xml file. Finally got a solution.
This is the main activity class
package com.example.android.tourguidekolkata;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
//lines of code
//lines of code
//lines of code
YourClass adapter = new YourClass(getSupportFragmentManager(), getApplicationContext());
//lines of code
// getApplicationContext() method passses the Context of main activity to the class TourFragmentPageAdapter
}
}
This is the non Activity class that extends FragmentPageAdapter
public class YourClass extends FragmentPagerAdapter {
private String yourStringArray = new String[4];
Context context;
public YourClass (FragmentManager fm, Context context)
{
super(fm);
this.context = context; // store the context of main activity
// now you can use this context to access any resource
yourStringArray[0] = context.getResources().getString(R.string.tab1);
yourStringArray[1] = context.getResources().getString(R.string.tab2);
yourStringArray[2] = context.getResources().getString(R.string.tab3);
yourStringArray[3] = context.getResources().getString(R.string.tab4);
}
@Override
public Fragment getItem(int position)
{
}
@Override
public int getCount() {
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return yourStringArras[position];
}
}
edited Oct 12 '17 at 8:42
hkutluay
5,47012342
5,47012342
answered Sep 6 '16 at 9:14
Satadru Saha
1
1
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7666589%2fusing-getresources-in-non-activity-class%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It's normally not a good idea to pass around
Contextobjects in Android. It can lead to memory leaks. See my answer for a less risky solution.– Jason Crosby
Aug 28 '13 at 18:34
possible duplicate of How to retrieve a context from a non-activity class?
– Richard Le Mesurier
May 21 '14 at 10:44