I have a library that I use in my application. In my library, I need to get a resource ( a bks file). I don't have a main activity in my library. How do I get a resource without an activity. Here is the code I have.
public class PostRequest {
Context context;
MyApplication application;
public String post(){
KeyStore trustStore = KeyStore.getInstance("BKS");
InputStream trustStoreStream = application.getResources().openRawResource(R.raw.certificate);
}
}
I am getting the error, Attempt to invoke virtual method getResources() on a null object reference.
I created a variable Context context to and used that context.getResources().openRawResource(R.raw.certificate); but still with no success. This is a library so I don't have MainActivity or any activity classes.
First of all,
contextandapplicationinstance variables are just references there.You haven't assigned the references yet so you can't use their method calls.
In analogous to an empty
envelope, you still haven't prepared aletterso you can't read or write it yet.Second, assuming that
MyApplicationis extended fromApplicationand also it is located in the library module as a standalone component, I recommend to remove it sinceApplicationclass defined inthe application using the libraryshall be used instead of the library one.IMO, if you are developing a library and require to use
context, just define it as a contsructor parameter or a method parameter and let the caller provides to you.OR if you ensure that your
MyApplicationclass defined can be used by the library, just define a staticcontextvariable there and use it (i.e.MyApplication.context). Just remember to usegetApplicationContext()there to avoid resources leakage.REF: Static way to get 'Context' in Android?