getResources() from static method, without context

為{幸葍}努か 提交于 2019-12-11 13:14:40

问题


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



来源:https://stackoverflow.com/questions/16277011/getresources-from-static-method-without-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!