【问题标题】:NullPointer on LayoutInflater - AndroidLayoutInflater 上的 NullPointer - Android
【发布时间】:2013-06-30 00:49:13
【问题描述】:

我在 MainActivity 中调用的另一个 java 文件中有一个类。我需要在外部类中增加一些布局。我遇到的问题是指定上下文,因为当我尝试扩展布局时,我得到一个空指针异常。该类没有自己的 onCreate() 方法,所以我需要从 MainActivity 传递上下文?不知道该怎么做。这导致我NullPointerException

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

NullPointerException on Context 上下文:

public class CameraListener extends Activity implements OnCameraChangeListener {

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


    Context context = getApplicationContext();

【问题讨论】:

  • 如果答案不起作用,粘贴整个类(没有方法,只是代码的相关部分)
  • 使用LayoutInflater.from(context)
  • NPE 在 LayoutInflater 之前

标签: android nullpointerexception android-context


【解决方案1】:

多个问题

第一

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

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

(学分:@Delyan)

LayoutInflater.from(context) 

第二

Context context = getApplicationContext();setContentView 之前不起作用。所以你需要在你的onCreate中调用setContentView之后初始化上下文

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

LayoutInflater 也一样,你需要在 onCreate 中初始化它

【讨论】:

  • 更好,LayoutInflater.from(context)
  • 好的,除了我在Context context = getApplicationContext();得到NPE
  • 粘贴整个类(没有无用的方法),以及你调用它的方法\
  • 这个类没有onCreate。这不是一个活动。
  • 如果你 extends Activity 你别无选择,伙计。你在想什么 ?这是 Android 编程的第一个基础知识,这里不假设纯 Java 规则。 Android 有一些基本的构造期望。
【解决方案2】:

Activity 扩展自 Context,这意味着您只需要在 onCreate() 方法中使用 LayoutInflater inflater = LayoutInflater.from(this);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多