空指针上LayoutInflater - Android电子 [英] NullPointer on 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屋!