简体   繁体   中英

Android- Null Pointer Exception in Implementing Interfaces during Communicating with Other Fragments

Been trying to implement Communicating with Other Fragments . There are errors during the selId.onIdSelected(pid.toString()) , and getting null pointer exception on this. I think I am not sure on what is the next thing to do. I am sure that when I click the current position has data but sending it to the other fragment is another thing.

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

              }
  } 

Fragment B

public class PlayerFragment extends ListFragment implements
                 SectionFragment.OnSelectedIdListener{

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

}
  1. It is good to follow naming conventions. The interface names begin with a capital letter and the method names begin with a small letter. So it's OnSelectedListener and idSelected respectively.
  2. While using listener, you should always check whether the listener is not null .
  3. You are implementing the interface in the Fragment whereas in your code, you are casting the Activity as the listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM