【问题标题】:Android- Null Pointer Exception in Implementing Interfaces during Communicating with Other FragmentsAndroid-在与其他片段通信期间实现接口时出现空指针异常
【发布时间】:2013-07-25 04:19:16
【问题描述】:

一直在尝试实现Communicating with Other FragmentsselId.onIdSelected(pid.toString()) 期间出现错误,并在此出现空指针异常。我想我不确定下一步该做什么。我确信当我单击当前位置时有数据但将其发送到另一个片段是另一回事。

  public  static class SectionFragment extends ListFragment {
     OnSelectedIdListener selId;

      public interface OnSelectedIdListener {
            public void onIdSelected(String position);
        }


        public void IdSelected(String id) {
            selId.onIdSelected(id);
        }

      public void onAttach(Activity activity) {
            super.onAttach(activity);

            try {
                 selId = (OnSelectedIdListener) activity;
            } catch (ClassCastException e) {
                Log.d("error!: ",
                        String.format(e.toString(), "helow"));
            }
      }  

      ....

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

            if(pid!=null){
                   Log.d("if not null here", "pid? "+ pid.toString());
                   selId.onIdSelected(pid.toString());
               }
            else{Log.d("Null selected id", ""+position);}

              }
  } 

片段 B

public class PlayerFragment extends ListFragment implements
                 SectionFragment.OnSelectedIdListener{

                @Override
                public void onIdSelected(String position) {
                    setSelectedId(position);
                }

}

【问题讨论】:

  • 确保您正在初始化 selId 或对其进行空检查。
  • @Abu,谢谢。我以某种方式正确地做到了?不知道我做错了什么。

标签: java android interface android-fragments


【解决方案1】:
  1. 最好遵循命名约定。接口名称以大写字母开头,方法名称以小写字母开头。所以分别是OnSelectedListeneridSelected
  2. 在使用监听器时,请务必检查监听器是否不是null
  3. 您在Fragment 中实现接口,而在您的代码中,您将Activity 强制转换为侦听器。

【讨论】:

  • 谢谢先生。您的示例代码将帮助我进一步理解您的解释。感谢您的考虑。
猜你喜欢
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 2021-06-29
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多