0

I have a resource xml file in res/raw named parameters.xml. This file is used through a class called Parameters. The class Parameters uses Xpath to extract data from an xml file.

In the main activity I've coded this:

Parameters parameters = new
Parameters(getResources().openRawResource(R.raw.parameters));

It works fine!

I want to test the Parameters class using the xml resource without Activity ==> I do not have context anymore

At the moment, I've coded a main method inside Parameters class (because I also use this class for other non android projects)

I've tried this:

1- Resources.getSystem().openRawResource(R.raw.parameter) - does not work because my xml file is not a system resources

2- create an inner class (inside main method) which extends InstrumentationTestCase - does not work : exception runtime stub!

Any idea to fix my problem ? Thanks

Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
Eric Valade
  • 121
  • 1
  • 5

3 Answers3

0

I do not think you can do that without the context instance. You can read more here.

Like someone pointed out it is best to get the resources inside of the Activity/Fragment and then pass it to the object, where you need it.

Community
  • 1
  • 1
Jernej K
  • 1,602
  • 2
  • 25
  • 38
0

You can create a static reference for your application like this:

public class YourApplicationClass extends Application{

    private static YourApplicationClass instance;

    public YourApplicationClass (){
        instance = this;
    }

    public static YourApplicationClass getInstance(){
            return instance;
    }
}

Then:

YourApplicationClass .getInstance().getResources().openRawResource(R.raw.parameters);

Add any point of your application will result getting the resources.

Also don't forget to add this inside application element in your manifest :

 android:name=".YourApplicationClass"
z3n105
  • 1,935
  • 1
  • 15
  • 14
  • It's normally not a good idea to pass around Context objects in Android. It can lead to memory leaks. You can read more [here](http://stackoverflow.com/questions/7666589/using-getresources-in-non-activity-class) – Jernej K Mar 22 '16 at 17:56
0

I've found a solution using Classloader and

java -ea -classpath
to execute

public static void main(String[] args) {
    Parameters parameters = new Parameters(ClassLoader.class.getClass().
    getResourceAsStream("/res/raw/parameters.xml"));
    ....
}

cd myprojectPath/app/src/main/java
javac Parameters.java
java -ea -classpath ".:../" Parameters
Eric Valade
  • 121
  • 1
  • 5