2013-07-02 40 views
0

我在另一个java文件中有一个类,在我的MainActivity中调用。我需要膨胀外部类中的一些布局。我遇到的问题是指定上下文,因为当我尝试膨胀布局时,我得到一个空指针异常。该类没有它自己的onCreate()方法,所以我需要从我的MainActivity传递上下文?不知道如何去做。这引起了我的NullPointerExceptionLayoutInflater上的NullPointer - Android

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

NullPointerExceptionContext方面:

public class CameraListener extends Activity implements OnCameraChangeListener { 

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


    Context context = getApplicationContext(); 
+0

如果答案不起作用,请粘贴整个类(没有方法,只是代码的相关部分) – Siddharth

+0

使用'LayoutInflater.from(context)'。 –

+0

NPE在LayoutInflater – ono

回答

2

多个问题

首先

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

你不应该需要的get ApplicationContext(),因为你已经拥有了它。

OR (学分:@Delyan)

LayoutInflater.from(context) 

Context context = getApplicationContext();setContentView前工作。因此,你需要在你onCreate

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

同一呼叫setContentView后,初始化上下文无二LayoutInflater,你需要在onCreate

+1

之前更好,'LayoutInflater.from(context)'。 – Delyan

+0

好吧,除了我在Context Context = getApplicationContext()上得到NPE外,' – ono

+0

粘贴整个类(没有无用的方法),用你调用这个的方法\ – Siddharth

0

Activity初始化它从Context延伸,这意味着你只需要LayoutInflater inflater = LayoutInflater.from(this);onCreate()方法。