View null inside fragment

只谈情不闲聊 提交于 2019-12-02 12:30:49

Override onViewCreated and move your

    unbinder = ButterKnife.bind(this, view);
    initialize();
    loadSkillsData();

into there

Use ViewTreeObserver.onGlobalLayoutListener to make sure the view is fully laid out before attempting to mutate it. Here is your loadSkillsData function using the global layout listener which should resolve your NPE:

private void loadSkillsData()
{
    Realm realm = getRealm();
    UserModel user = realm.where(UserModel.class).findFirst();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(RestAPI.ENDPOINT)
            .addConverterFactory(MoshiConverterFactory.create())
            .build();
    RestAPI restApi = retrofit.create(RestAPI.class);
    Call<ResponseSkills> loginCall = restApi.getSkills(user.getServerUserId());
    loginCall.enqueue(new Callback<ResponseSkills>()
    {
        @Override
        public void onResponse(Call<ResponseSkills> call, final Response<ResponseSkills> response)
        {
            if (response.isSuccessful())
            {
                if (response.body().getStatus())
                {
                    skillList = response.body().getSkillList();
                    ArrayAdapter<SkillModel> skillAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, skillList);
                    autocompleteService.viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            autocompleteService.setAdapter(skillAdapter);
                        }
                    }
                }
                else
                {
                    switch (response.body().getError())
                    {
                        default:
                        Toasty.error(context, response.body().getError());
                        break;
                    }
                }
            } else
            {
                Toasty.error(context, getString(R.string.toast_experienced_a_problem)).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseSkills> call, Throwable t)
        {
            Toasty.error(context, getString(R.string.toast_experienced_a_problem)).show();
            t.printStackTrace();
        }
    });
}

In addition to the problem with the NPE, you are also going to run into problems with the way you are using realm. Realm needs to be accessed on it's own thread, it will cause crashes in your app if you access it from the UI thread like you are doing in your code above.

You have to call ButterKnife.bind in onCreateView method

     // bind the view using butterknife
    ButterKnife.bind(this);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!