空指针上LayoutInflater - Android电子 [英] NullPointer on LayoutInflater - Android

查看:184
本文介绍了空指针上LayoutInflater - Android电子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我打电话,我MainActivity另一个Java文件中的类。我需要一些充气布局在外部类中。我遇到的问题是指定的范围内,因为当我试着吹大的布局,我得到一个空指针异常。本类不具有它自己的的onCreate()的方法,所以我需要从我的MainActivity通过上下文?不知道如何去做。这是导致我的 NullPointerException异常

 上下文的背景下= getApplicationContext();
LayoutInflater吹气=(LayoutInflater)context.getApplicationContext()。getSystemService(Context.LAYOUT_INFLATER_SERVICE);;

NullPointerException异常上下文背景:

 公共类CameraListener扩展活动实现OnCameraChangeListener {    私有静态最终诠释SCALE_HEIGHT = 50;
    GoogleMap的MMAP;
    GoogleC3iActivity mParent;
    上下文的背景下= getApplicationContext();


解决方案

多重问题

第一

 上下文的背景下= getApplicationContext();
LayoutInflater吹气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

您不应该需要getApplicationContext(),因为你已经拥有它。

(学分:@Delyan)

  LayoutInflater.from(上下文)

上下文的背景下= getApplicationContext(); 的setContentView 不起作用。所以,你需要你打电话后,初始化背景的setContentView 的onCreate

  @覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.home);
    上下文= getApplicationContext();

也是一样的 LayoutInflater ,你需要初始化它的的onCreate

I have a class in another java file that I'm calling in my MainActivity. I need to inflate some layouts in the external class. The problem I'm having is specifying the context, because when I try to inflate the layouts I get a Null Pointer Exception. The class doesn't have it's own onCreate() method so I need to pass the context from my MainActivity? Not sure how to go about it. This is causing me the NullPointerException:

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

NullPointerException on Context context:

public class CameraListener extends Activity implements OnCameraChangeListener {

    private static final int SCALE_HEIGHT = 50;
    GoogleMap mMap;
    GoogleC3iActivity mParent;


    Context context = getApplicationContext();

解决方案

Multiple Issues

First

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

You shouldn't need the getApplicationContext(), since you already have it.

OR (credits : @Delyan)

LayoutInflater.from(context) 

Second

Context context = getApplicationContext(); does not work before setContentView. So you need to initialize context after you call setContentView in your onCreate

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    context = getApplicationContext() ;

Same goes for LayoutInflater, you need to initialize it in the onCreate

这篇关于空指针上LayoutInflater - Android电子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆