java.lang.NullPointerException: 尝试在空对象引用上调用接口方法'OnColorChangeListener.colorChanged(java.lang.String)'

7

我是一名Android初学者,如果这是一个超级简单的修复操作,请谅解。我已经查看了其他帖子关于同样的空指针异常问题,但是我仍然找不到代码中错误的源头。

我有一个非常简单的项目,其中包含Main Java类和Fragment类。当用户点击单选按钮时,主活动的背景颜色必须更改,但是我一直收到以下错误提示:

java.lang.NullPointerException: 尝试在空对象引用上调用接口方法'OnColorChangeListener.colorChanged(java.lang.String)'。

Activity5.java:

public class Activity5 extends AppCompatActivity implements ColorFragment.OnColorChangeListener {

    LinearLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_5);
        linearLayout = (LinearLayout)findViewById(R.id.main_layout_id);
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ColorFragment colorFragment = new ColorFragment();
        fragmentTransaction.add(R.id.fragment_container, colorFragment);
        fragmentTransaction.commit();
    }

    @Override
    public void colorChanged(String colorname) {
        if(colorname.equals("RED")) {
            linearLayout.setBackgroundColor(Color.RED);
        }
        else if(colorname.equals("GREEN")) {
            linearLayout.setBackgroundColor(Color.GREEN);
        }
        else if(colorname.equals("BLUE")){
            linearLayout.setBackgroundColor(Color.BLUE);
        }

        else if(colorname.equals("MAGENTA")) {
            linearLayout.setBackgroundColor(0xffff00ff);
        }
        else if(colorname.equals("YELLOW")) {
            linearLayout.setBackgroundColor(0xffffff00);
        }

    }
} 

现在这里是Fragment类:
public class ColorFragment extends Fragment {

    OnColorChangeListener onColorChangeListener;


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

        RadioGroup radioButtonGroup = (RadioGroup)view.findViewById(R.id.color_radio_group);
        radioButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup group, int checkIdOfButton) {

                switch (checkIdOfButton){
                    case R.id.red_id:
                        onColorChangeListener.colorChanged("RED");
                        break;
                    case R.id.green_id:
                        onColorChangeListener.colorChanged("GREEN");
                        break;
                    case R.id.blue_id:
                        onColorChangeListener.colorChanged("BLUE");
                        break;
                    case R.id.magenta_id:
                        onColorChangeListener.colorChanged("MAGENTA");
                        break;
                    case R.id.yellow_id:
                        onColorChangeListener.colorChanged("YELLOW");
                        break;
                }
            }
        });

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            onColorChangeListener = (OnColorChangeListener) context;
        }
        catch catch (Exception e){}
        }
    }
    public interface OnColorChangeListener
    {
        public void colorChanged(String colorname);
    }
}

这里是XML活动:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.user.seriousapp.Activity5"
    tools:showIn="@layout/activity_5"
    android:id="@+id/main_layout_id">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Fragment Communication Example"
        android:id="@+id/textView2"
        android:textColor="#000000"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:id="@+id/fragment_container"
        android:layout_marginTop="60dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:gravity="center"></RelativeLayout>

</LinearLayout>

最后这里是XML片段:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="250dp"
    android:background="#000000">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Select a Color"
        android:textColor="#ffffff"
        android:id="@+id/textView3"
        android:layout_gravity="center_horizontal" />

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:orientation="vertical"
        android:id="@+id/color_radio_group">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RED"
            android:textColor="#ffffff"
            android:buttonTint="#ffffff"
            android:id="@+id/red_id" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GREEN"
            android:textColor="#ffffff"
            android:buttonTint="#ffffff"
            android:id="@+id/green_id" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="BLUE"
            android:textColor="#ffffff"
            android:buttonTint="#ffffff"
            android:id="@+id/blue_id" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MAGENTA"
            android:textColor="#ffffff"
            android:buttonTint="#ffffff"
            android:id="@+id/magenta_id" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="YELLOW"
            android:textColor="#ffffff"
            android:buttonTint="#ffffff"
            android:id="@+id/yellow_id" />

    </RadioGroup>
</LinearLayout>

一个快速的浏览实际上看起来不错。如果你在片段的onAttach方法中删除 try...catch语句或在catch中打印一些内容到logcat中,会发生什么?我只是想确保onAttach方法的上下文确实实现了OnColorChangeListener接口。 - George Mulligan
它没有向logcat写入任何内容,我猜这意味着该方法没有被调用。 - user2590243
看一下我的回答。你的设备可能不是API级别23,这是新的onAttach方法被添加的时候。 - George Mulligan
哇,那个有效了,非常感谢!还有一个快速的问题,我在同一台设备上使用了onAttach()方法来处理其他项目,它正常工作(重写该方法)。为什么它可以在一个项目上工作,但在同一台设备上的另一个项目上却不行呢? - user2590243
我最好的猜测是其他项目正在使用 onAttach(Activity activity),而不是较新的需要使用 Context 的版本。您还可以检查其他项目中构建文件中的 targetSdkVersion。如果它小于23,则无法使用使用 Context 的新方法。另一个想法是,在其他项目中可能正在使用支持库,并且据说即使在API 23以下的设备上调用 onAttach(Context context)也可以正常工作。 - George Mulligan
显示剩余2条评论
2个回答

6

很有可能你需要覆盖重载版本的onAttach(Activity activity)方法,因为另一个需要Context参数的方法没有被调用。这很可能是因为你的Android设备不是API 23+,而你使用的方法版本是在API 23中添加的。

@Override
public void onAttach(Activity activity) {
    super.onAttach(context);

    try {
        onColorChangeListener = (OnColorChangeListener) context;
    }
    catch catch (Exception e){
        // you should really do something here with this exception
    }
}

编辑

或者切换到使用包含支持片段管理器和片段的支持库。

这样即使在 API 23 之前的设备上,也应该正确调用 onAttach(Context context)


非常感谢,这个方法很有效。我唯一剩下的问题是,为什么我在其他项目中重写了onAttach(context)方法,并且在使用同一设备进行此项目时它也起作用? - user2590243
看看我在你的问题下面的倒数第二个评论。我在那里给出了一些猜测,其中一个应该是原因。 - George Mulligan
当然,努力想出如何做到这一点。 - user2590243

2
尝试在onCreate()onActivityCreated()方法中使用getActivity()初始化监听器。请注意保留HTML标签。
onColorChangeListener = (OnColorChangeListener) getActivity();

谢谢。之前的帖子实际上已经修复了错误,但我一定会记住这个。 - user2590243
这个在onActivityCreated()中对我非常有效,谢谢。 - Armando Marques da S Sobrinho

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