getResources() from static method, without context

2019-09-09 20:31发布

问题:

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 something like:

public static final Context context = XXX;

It should be possible right? Since I'm obviously only calling from the current app and both resources and databases are shared inside the app.

To be clear: I want to access Resources and the SQLiteDatabases (if I happen to be wrong about the context approach).

Is it possible to achieve?

Edit: Is it possible to get the context from inside something like this (without passing it as a parameter)

public class foo{
    foo(){
        XXX.getResources();
    }
}

Edit2: Trying @britzl:s fist idea

public class SpendoBase extends Application{
private static Context context;
public SpendoBase(){
    System.out.println("SPENDOBASE: " + this);
    System.out.println("SPENDOBASE: " + this.getBaseContext());
}
public static Context getContext(){
    return this.context;
}

}

How do i get hold of the context? Either in the constructor or form the getContext();

Ps the getBaseContext() returns null, and getApplicationContext thows a nullPointerException.

回答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:

    public class BaseApplication extends Application {
    
        private static BaseApplication instance;
    
        public BaseApplication() {
            super();
            instance = this;
        }
    
        public static BaseApplication getInstance() {
            return instance;
        }
    }
    

    And in AndroidManifest.xml:

    <application android: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