Skip to content Skip to sidebar Skip to footer

Getresources() From Static Method, Without Context

I'm working on a SQLiteOpenHelper from which I'll read databases via static methods (since the databases are shared anyway). Is it possible to get the application context to someth

Solution 1:

I see three possible solutions to your problem:

  1. Create your own subclass of Application and set that as your application class in the manifest file. In your subclass you could have a static getInstance() method that would provide you with the application context (and thus Resources) from anywhere within your application. Example:

    publicclassBaseApplicationextendsApplication {
    
        privatestatic BaseApplication instance;
    
        publicBaseApplication() {
            super();
            instance = this;
        }
    
        publicstatic BaseApplication getInstance() {
            return instance;
        }
    }
    

    And in AndroidManifest.xml:

    <applicationandroid:name="com.example.BaseApplication"...>
        ...activities
    </application>
  2. Pass a context to any calls you make in your SQLiteOpenHelper

  3. Inject the Resources instance using dependency injection

Post a Comment for "Getresources() From Static Method, Without Context"