双击图标侦听器时发生应用程序崩溃

时间:2017-08-09 13:20:42

标签: android android-fragments nullpointerexception onclicklistener

我有一个工具栏Fragment被调用,主要片段中定义了一个左图标监听器的属性(定义如下)

工具栏片段(常用工具栏片段随处可用作标题)

public void refresh(commonFragment f) {
        if (view != null && f != null && !commonFragment .class.equals(f.getClass()) && !BlankcommonFragment .class.equals(f.getClass())) {

            setRightIcon(f.getRightIcon(), f.getRightIconListener());
            setLeftIcon(f.getLeftIcon(), f.getLeftIconListener());


        }
    }

Common Fragment (此处保留常用属性以供重复使用)

     public Integer getLeftIcon() {
            return R.drawable.left_fragment_icon;
        }

        public View.OnClickListener getLeftIconListener() {
            return new NavigationOnClickListener(this, new LeftFragment());
        }
 public View.OnClickListener getRightIconListener() {

        return MenuFragment.instance().getDashboardIconListener();
    }

页面片段(左侧图标侦听器发生问题的页面)

 @Override
    public Integer getLeftIcon() {
        return R.drawable.back_icon;
    }

    @Override
    public View.OnClickListener getLeftIconListener() {

        return new NavigationOnClickListener(this, new HomeFragment());
    }

NavigationOnClickListener (用于导航)

public class NavigationOnClickListener implements View.OnClickListener {
    private Common Fragment from;
    private Common Fragment to;

    public NavigationOnClickListener(Common Fragment from, Common Fragment to) {
        this.from = from;
        this.to = to;
    }

    @Override
    public void onClick(View v) {
        from.navigate(to);
    }
}

后退按钮图标和左侧图标根据不同的页面切换(相同的图像视图但具有不同的图像ID)。
例如:
有3个碎片:A,B和C,B是Home Fragment 通过单击B上的左侧图标,您将转到A,然后单击C上的后退图标将您带到B

问题双击后退图标会使应用程序崩溃

NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

在views.setAdapter上出现错误

    public View build(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { //line added 

         ...

    View home = inflater.inflate(R.layout.fragment_home, container, false);

    final Activity activity = this.getActivity();
    final HomeFragment fragment = this; 

         @Override
        public void onSuccess(Call<List<xyzView>> call, Response<List<xyzView>> response) {
            ListView views = (ListView) container.findViewById(R.id.course_list);
            views.setAdapter(new xyzAdapter(activity, R.layout.fragment_home_item, response.body(), fragment));

如何防止多次点击后退按钮时发生崩溃?

1 个答案:

答案 0 :(得分:0)

通过在正确的XML布局中找到它来阻止视图上的nullpointerexception。

例如,如果该列表视图位于fragment_home.xml ...

View home = inflater.inflate(R.layout.fragment_home, container, false);
final ListView views = (ListView) home.findViewById(R.id.course_list);

... 

    @Override
    public void onSuccess(Call<List<xyzView>> call, Response<List<xyzView>> response) {

        views.setAdapter(new xyzAdapter(getActivity(), R.layout.fragment_home_item, response.body(), HomeFragment.this));