SoluableNonagon
SoluableNonagon

Reputation: 11755

Android - Read properties file without using context

I have a simple class which is not an activity, so I don't have access to context, but I want to read a properties file in my project (rather than on sd card).

MyClass {

    public static void readProperties(){
        Properties props=new Properties();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("/mine.properties");
        try {
            props.load(inputStream); 
        } catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

When I run the code though, I get a null pointer exception:

02-20 15:32:38.396: E/AndroidRuntime(27473): java.lang.NullPointerException: in == null
02-20 15:32:38.396: E/AndroidRuntime(27473): at java.util.Properties.load(Properties.java:246)

Where should I put my properties file in order to be able to read it? I tried src , the project root, assets, and also next to MyClass.java, each time getting null pointers. What am I doing wrong?

I'm using Eclipse with ADT (not on Android Studio yet).
My structure is something like this:

-src
--main/SomeActivity.java
--main/MyClass.java
--main/mine.properties
-assets
-gen
-res

Upvotes: 1

Views: 1432

Answers (1)

ataulm
ataulm

Reputation: 15334

I use gradle.properties to store some things like API key. Gradle properties are simple key value pairs:

tmdbApiKey=1a2b3c4d5e6f7g8h9i0j6f7g8h9i0j

The properties file is in the root of my Android project:

/Wutson
  gradle.properties
  ... other files/directories
  mobile/
    build.gradle

In /Wutson/mobile/build.gradle which is the build file for my Android module, I read from my properties file, and use the buildConfigField method to generate a static final field in my BuildConfig class which is accessible at runtime from classes in my Android module.

apply plugin: 'com.android.application'

...

def tmdbApiKey = hasProperty('tmdbApiKey') ? tmdbApiKey : 'provide this in gradle.properties'

android {
    ...

    defaultConfig {
        ...

        buildConfigField "String", "TMDB_API_KEY", "\"$tmdbApiKey\""
    }

    ...
}

From a class in my Android module, for example, MainActivity, I'm able to access this value:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("TEST", "my api key: " + BuildConfig.TMDB_API_KEY);
}

will print:

TEST | my api key: 1a2b3c4d5e6f7g8h9i0j6f7g8h9i0j

unless you forgot to put that property in the file in which case you'd get:

TEST | my api key: provide this in gradle.properties

A full example can be found at my project repo on GitHub (where gradle.properties.example is an example of what gradle.properties would look like).

Upvotes: 2

Related Questions