在与其他片段通信期间实现接口的Android-Null指针异常

时间:2013-07-25 04:19:16

标签: java android interface android-fragments

一直在尝试实施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);
                }

}

1 个答案:

答案 0 :(得分:1)

  1. 遵循命名约定是很好的。接口名称以大写字母开头,方法名称以小写字母开头。所以它分别是OnSelectedListeneridSelected
  2. 使用侦听器时,应始终检查侦听器是否不是null
  3. 您正在Fragment中实现接口,而在您的代码中,您正在将Activity作为侦听器进行转换。