【问题标题】:java.lang.NullPointerException: Attempt to invoke interface method 'OnColorChangeListener.colorChanged(java.lang.String)' on a null object reference [duplicate]java.lang.NullPointerException:尝试在空对象引用上调用接口方法“OnColorChangeListener.colorChanged(java.lang.String)”[重复]
【发布时间】:2016-04-23 03:37:45
【问题描述】:

我是 Android 的初学者,如果这是一个超级简单的解决方法,请原谅我。我已经查看了此处有关相同 NullPointerException 问题的其他帖子,但是我仍然无法在我的代码中找到错误的来源。

我有一个非常简单的项目,它有 Main java 类和一个片段类。当用户单击单选按钮时,主要活动的背景颜色必须改变,但我不断收到:

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);
        }

    }
} 

现在是片段类:

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 语句或在捕获中打印一些内容到logcat 会发生什么?我只是想确保onAttach 方法中的上下文真正实现了OnColorChangeListener 接口。
  • 我像这样删除了 try..catch 但它不起作用,当我单击任何单选按钮时,我得到:“不幸的是 SeriousApp 已停止”:public void onAttach(Context context) { super. onAttach(上下文); onColorChangeListener = (OnColorChangeListener) 上下文;我将如何在 catch 中向 logcat 打印一些东西?
  • 最后一次测试抱歉,我一开始就应该这么说。尝试从 onAttach 方法内部打印一些内容到 Logcat 以查看该方法是否真的被调用。 Log.e("ColorFragment", "Inside onAttach");
  • 它没有向logcat写入任何内容,我猜这意味着该方法没有被调用。
  • 右看我的回答。您的设备可能不是 API 级别 23,此时添加了新的 onAttach 方法。

标签: java android android-fragments nullpointerexception radio-button


【解决方案1】:

您可能需要覆盖片段中的重载版本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) 方法并且它在这个设备上工作的,这与我目前用于这个项目的设备相同?
  • 在你的问题下看我倒数第二个comment。我在那里做了一些猜测。其中一个应该是原因。
  • 当然,想知道怎么做。
【解决方案2】:

尝试使用getActivity()onCreate()onActivityCreated()方法中初始化监听器

onColorChangeListener = (OnColorChangeListener) getActivity();

【讨论】:

  • 谢谢。上一篇文章实际上修复了错误,我一定会记住这一点。
  • onActivityCreated() 中的这项工作对我来说就像一个魅力,谢谢
猜你喜欢
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2018-02-05
  • 2015-11-13
  • 2018-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多