0

The code is followed:

Context c = getContext().createPackageContext("com.master.schedule", Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY);

int id = c.getResources().getIdentifier("layout_main", "layout","com.master.schedule"); LayoutInflater inflater = LayoutInflater.from(c); piflowView = inflater.inflate(id, null);

com.master.schedule is my package project.The upside code presents how the other project(his package name is different to mine) inflate my project, in my project there is only a ViewGroup(I don't have an activity); and when I invoke "context.getApplicationContext", it returns null... my project code is below:

public class CascadeLayout extends RelativeLayout {
    private Context context;
    public CascadeLayout(Context context) {
        super(context);
        this.context=context.getApplicationContext();
    }
     @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //here: context == null;
    }
}

I find the createPackageContext() give the "Context c" to me is a ContextImpl type; I think that's caused return null;

So how can I get an ApplicationContext which not null?

BTW:please don't persuade me don't invoke getApplicationContext();As I must use an .jar, the jar need to invoke getApplicationContext() in it;

thanks very very much.

JoeKevin
  • 81
  • 3
  • 12
  • on what object you are calling `getApplicationContext()`? also you are using wrong package in your code... – pskink Jan 22 '16 at 02:46
  • Forgive my English expression, I have update my questions, where my context.getApplicationContext(); thanks! – JoeKevin Jan 22 '16 at 03:03

1 Answers1

3

The documentation for createPackageContext() states:

Return a new Context object for the given application name. This Context is the same as what the named application gets when it is launched, containing the same resources and class loader.

Reading a bit between the lines, this context is apparently supposed to be "the same" as an application context. However, you are seeing that its getApplicationContext() returns null, so we can attempt to fix that by using a ContextWrapper (see below). Hopefully, this approach will be good enough for your needs.

In the following code, WrappedPackageContext is used to wrap the "package context" returned by createPackageContext(), overriding the getApplicationContext() implementation so that it returns itself.

class WrappedPackageContext extends ContextWrapper {
    WrappedPackageContext(Context packageContext) {
        super(packageContext);
    }

    @Override
    public Context getApplicationContext() {
        return this;
    }
}

Context createApplicationContext(Context packageContext) {
    return new WrappedPackageContext(packageContext);
}
cybersam
  • 63,203
  • 6
  • 53
  • 76