Home > Back-end >  Get Resource fro raw folder without activity
Get Resource fro raw folder without activity

Time:11-08

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.

CodePudding user response:

First of all, context and application instance 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 a letter so you can't read or write it yet.


Second, assuming that MyApplication is extended from Application and also it is located in the library module as a standalone component, I recommend to remove it since Application class defined in the application using the library shall 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.

public class PostRequest {
    Context context;
    MyApplication application;

 // Constructor to ask for context
 public PostRequest(Context _context) {
   this.context = _context;
 }

 // Method signature to ask for context
 public String post(Context context){
    KeyStore trustStore = KeyStore.getInstance("BKS");
    InputStream trustStoreStream = context.getResources().openRawResource(R.raw.certificate);
}
}

OR if you ensure that your MyApplication class defined can be used by the library, just define a static context variable there and use it (i.e. MyApplication.context). Just remember to use getApplicationContext() there to avoid resources leakage.

REF: Static way to get 'Context' in Android?

CodePudding user response:

add constructor to your class:

public class PostRequest {
    Context context;
    MyApplication application;

    public  PostRequest(Context context,MyApplication application){
        this.context = context;
        this.application = application;;
    }

    public String post(){
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream trustStoreStream = context.getResources().openRawResource(R.raw.certificate);
    }
}

  • Related