有时,在UIThread上访问时,使用@ViewById注释的字段将返回null

时间:2017-08-09 08:06:02

标签: java android android-annotations findviewbyid android-runonuithread

我有一个使用AndroidAnnotations@ViewById注释的课程。我看到很多崩溃,因为@ViewById注释的某些字段为空。

  

尝试调用虚方法' void com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout.setRefreshing(boolean)'在null对象引用上    

中有两个问题

这是班级的一部分:

@EFragment(R.layout.fragment_categories_tab)
public class CategoriesTabFragment extends BaseFragment implements CategoryAdapter.OnItemSelected, SwipyRefreshLayout.OnRefreshListener {
    @ViewById(R.id.swipeRefreshLayout)
    protected SwipyRefreshLayout swipeRefreshLayout;
    @ViewById(R.id.placeholder_textview)
    protected CustomTextView statusLabel;

    private void loadChildren() {
        AndroidUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true); //crash happens here, but not always
            }
        });
    }

    categoryService.getCategories(new CommListener<Pair<Category[], Boolean>>() {
            @Override
            public void onSuccess(NetworkResult result, Pair<Category[], Boolean> object) {
                AndroidUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null) {
                            statusLabel.setText(""); //another point that crash happens, but again sometime and only in early stage of the fragment's life
                        }
                    }
            }
    }
}

这是AndroidUtil类:

public class AndroidUtil {
    private static Handler mainHandler = new Handler(Looper.getMainLooper());

    public static void runOnUiThread(Runnable runnable) {
        mainHandler.post(runnable);
    }
}

我是Android新手;而且我似乎找不到原因。我提前感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

AndroidUtil.runOnUiThread更改为getActvity()并在使用前检查null。

在你的情况下,它会崩溃,因为有时候你的片段没有附加到Activity上,所以你在里面的所有布局都是null。