NullPointerException异常访问视图的onCreate() [英] NullPointerException accessing views in onCreate()

查看:211
本文介绍了NullPointerException异常访问视图的onCreate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是经常张贴在StackOverflow的一个问题,一个典型的问题。

我下面的教程。我创建使用向导创建新的活动。我得到 NullPointerException异常试图调用查看的方法时,S采用 findViewById()获得在我的活动的onCreate()

活动的onCreate()

  @覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    查看东西= findViewById(R.id.something);
    something.setOnClickListener(新View.OnClickListener(){...}); // NPE这里

    如果(savedInstanceState == NULL){
        getSupportFragmentManager()的BeginTransaction()
                。新增(R.id.container,新PlaceholderFragment())提交()。
    }
}
 

布局XML( fragment_main.xml ):

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    工具:上下文=packagename.MainActivity $ PlaceholderFragment>

    <查看
        机器人:layout_width =100dp
        机器人:layout_height =100dp
        机器人:ID =@ + ID /某事/>

< / RelativeLayout的>
 

解决方案

本教程可能是过时的,试图创建一个基于活动的用户界面,而不是由向导生成的code pferred片段为基础的UI $ P $

视图是在片段布局( fragment_main.xml ),而不是在活动布局( activity_main.xml )。 的onCreate()是在生命周期为时尚早找到它在活动视图层次和返回。在调用一个方法会导致NPE。

在preferred的解决方案是将code的片段 onCreateView(),要求 findViewById()上的充气段布局 rootView

  @覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
    捆绑savedInstanceState){
  查看rootView = inflater.inflate(R.layout.fragment_main,集装箱,
      假);

  查看东西= rootView.findViewById(R.id.something); //不活动findViewById()
  something.setOnClickListener(新View.OnClickListener(){...});

  返回rootView;
}
 

作为一个侧面说明,片段布局,最终将活动视图层次的一部分和发现具有活性 findViewById(),但片段交易已经运行后,才。待处理片段交易得到执行super.onStart()的onCreate()

This is a canonical question for a problem frequently posted on StackOverflow.

I'm following a tutorial. I've created a new activity using a wizard. I get NullPointerException when attempting to call a method on Views obtained with findViewById() in my activity onCreate().

Activity onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

Layout XML (fragment_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>

解决方案

The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code.

The view is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

The preferred solution is to move the code to the fragment onCreateView(), calling findViewById() on the inflated fragment layout rootView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_main, container,
      false);

  View something = rootView.findViewById(R.id.something); // not activity findViewById()
  something.setOnClickListener(new View.OnClickListener() { ... });

  return rootView;
}

As a side note, the fragment layout will eventually be a part of the activity view hierarchy and discoverable with activity findViewById() but only after the fragment transaction has been run. Pending fragment transactions get executed in super.onStart() after onCreate().

这篇关于NullPointerException异常访问视图的onCreate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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