简体   繁体   中英

layoutinflater nullpointerexception in android

I want to set Activity in FrameLayout . Here is my code:

FrameLayout fl = new FrameLayout(this);
fl = (FrameLayout ) findViewById(R.id.actioncontent);           
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);           
View myview =LayoutInflater.from(this).inflate(R.layout.wallpaper, null);
fl.removeAllViews();
fl.addView(myview);

I am getting an error NullPointerException .

You need to use inflator insteed of LayoutInflater.from(this)

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View myview =LayoutInflater.from(this).inflate(R.layout.wallpaper, null);
            fl.removeAllViews();
                fl.addView(myview);

Replace above code with below

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View myview =inflater .inflate(R.layout.wallpaper, null);
            fl.removeAllViews();
                fl.addView(myview);

You didn't state what 'this' was, or where the NPE is happening - but it could be that 'this' presents the wrong context. Try using your activity name instead? For instance, MainActivity.this

Also, as was stated below me, replace from View myview =LayoutInflater.from(this).inflate to View myview = inflater.inflate

change

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

to

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM