java.lang.NullPointerException: 尝试在 null 对象引用上调用虚拟方法 'android.view.View android.view.View.findViewById(int)'

7

我有一个BlankFragment

package com.hfad.addingafragmenttoframelayout;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.w3c.dom.Text;


/**
 * A simple {@link Fragment} subclass.
 */
public class BlankFragment extends Fragment {


    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("message","onCreateView() of BlankFragment");
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    public void setText(String textToBeSet){
        TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);
        tv.setText(textToBeSet);
    }

}

它的布局如下:

<FrameLayout 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"
    tools:context="com.hfad.addingafragmenttoframelayout.BlankFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment"
        android:id="@+id/fragmentText"/>

</FrameLayout>

这里是MainActivity
package com.hfad.addingafragmenttoframelayout;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //BlankFragment bf = new BlankFragment();
        //getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, bf).commit();

        BlankFragment bf = new BlankFragment();
        bf.setText("hello world");
        getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, bf).commit();


    }




}

这里是MainActivity的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.hfad.addingafragmenttoframelayout.MainActivity"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fragment_container"
        />


</LinearLayout>

在活动的onCreate方法中,我正在将片段添加到布局中。这个方法很好用,除非我尝试使用setText方法更改文本。然后就会出现以下错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                           at com.hfad.addingafragmenttoframelayout.BlankFragment.setText(BlankFragment.java:35)
                                                                                           at com.hfad.addingafragmenttoframelayout.MainActivity.onStart(MainActivity.java:29)

提到这行
TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);

有人能解释一下是什么导致了这个异常吗?


2
可能是Nullpointer exception的重复问题。 - Vikrant Kashyap
1
在执行 getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, bf).commit(); 后,尝试使用 bf.setText("hello world");。 - xAqweRx
6个回答

24

不要

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d("message","onCreateView() of BlankFragment");
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

public void setText(String textToBeSet){
    TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText);
    tv.setText(textToBeSet);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
{

    View RootView = inflater.inflate(R.layout.fragment_blank, container, false);
    
    TextView tv = (TextView)RootView.findViewById(R.id.fragmentText);
    tv.setText("HI");
    
    return RootView;
}

我明白你的意思,但问题在于我自己创建了BlankFragment的对象,因此onCreateView没有被调用。有没有一种方法可以在实例化对象时调用片段的生命周期方法? - user4913383

1
问题在于FragmentTransaction默认是异步的
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_container, BlankFragment.newInstance);
ft.disallowBackStack();
ft.commitNowAllowingStateLoss();

然后你仍然无法获得Fragment,你需要从FragmentTransaction中获取它。
BlankFragment bf = (BlankFragment) getSupportFragmentManager().getFragmentById(R.id.fragment_container);
bf.setText("hello world");

这篇文章帮助我更好地理解了这个问题


1
谢谢,但是这是关于commitNow()而不是commit()的问题。在你的情况下,你是正确的,设置文本太早了。你应该在片段的onCreateView()onViewCreated()中设置它。 - CoolMind

1
这里:
bf.setText("hello world");

这行代码出现问题,因为在将Fragment添加到FragmentManager之前调用了FragmentsetText方法。

在添加bf Fragment之后再调用setText方法:

    getSupportFragmentManager().beginTransaction().
    add(R.id.fragment_container, bf).commit();
    bf.setText("hello world"); // call here

这并没有产生任何不同。我还是得到同样的错误。 - user4913383

0
TextView tv = (TextView)this.getView().findViewById(R.id.fragmentText); 

在onCreateView()中完成它。


0

在视图尚未创建时,您可以使用一个临时变量来保存 String

private TextView tv;
private String holder = ""; 

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_blank, container,false);

    tv = (TextView)v.findViewById(R.id.fragmentText);
    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
   tv.setText(holder);
}

public void setText(String textToBeSet){
    if(tv != null){
       tv.setText(textToBeSet);
    }else{
       holder = textToBeSet;
    }
}

0

我的假设是您想要实例化带有一些初始文本的BlankFragment,并允许稍后从MainActivity设置文本。

在这种情况下,我首先会更改片段以接受初始文本,如下所示:

public class BlankFragment extends Fragment {
    private static final String ARG_INITIAL_TEXT = "arg_initial_text";

    public static BlankFragment newInstance(CharSequence initialText) {
        final BlankFragment fragment = new BlankFragment();
        final Bundle args = new Bundle();
        args.putCharSequence(ARG_INITIAL_TEXT, initialText);

        fragment.setArguments(args);
        return fragment;
    }

    public BlankFragment() {
        // Required empty public constructor
    }

    private CharSequence mInitialText;
    private TextView mText;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInitialText = getArguments().getCharSequence(ARG_INITIAL_TEXT);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("message", "onCreateView() of BlankFragment");
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mText = view.findViewById(R.id.fragmentText);

        mText.setText(mInitialText);
    }

    public void setText(CharSequence textToBeSet) {
        mText.setText(textToBeSet);
    }
}

然后,Activity 代码将如下所示:

public class MainActivity extends AppCompatActivity {
    private BlankFragment mBlankFragment;

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

        if (savedInstanceState == null) {
            final Fragment bf = BlankFragment.newInstance("hello world");
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.fragment_container, bf, BlankFragment.class.getName())
                    .commit();
        }

        mBlankFragment = (BlankFragment) getSupportFragmentManager()
                .findFragmentByTag(BlankFragment.class.getName());
    }

    private void someTimeLaterWhenWantingToSetNewTextToFragmentFromActivity(CharSequence newText) {
        if (mBlankFragment != null) {
            mBlankFragment.setText(newText);
        }
    }
}

请注意,对savedInstanceState进行空值检查是为了防止由于配置更改等原因导致的Activity重新创建。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接