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);
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
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.
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;
}
}
Do you have access to the Context? Or most likely you can get access to it by getApplicationContext()
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);
this can be done by using
context.getResources().getXml(R.xml.samplexml);
We can use context Like this try now Where the parent is the ViewGroup.
Context context = parent.getContext();
well no need of passing the context and doing all that...simply do this
Context context = parent.getContext();
Edit: where parent is the ViewGroup
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);
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 simple class declare context and get data from file from res folder
public class FileData
{
private Context context;
public FileData(Context current){
this.context = current;
}
void getData()
{
InputStream in = context.getResources().openRawResource(R.raw.file11);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//write stuff to get Data
}
}
In the activity class declare like this
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileData fileData=new FileData(this);
}
}
来源:https://stackoverflow.com/questions/7666589/using-getresources-in-non-activity-class