View null inside fragment

前端 未结 2 388
猫巷女王i
猫巷女王i 2021-01-28 12:46

I\'ve been working on this for hours now. Can\'t find any reason. I can\'t post the entire fragment here but the following should make it clear.

@BindView(R.id.a         


        
2条回答
  •  礼貌的吻别
    2021-01-28 12:59

    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 loginCall = restApi.getSkills(user.getServerUserId());
        loginCall.enqueue(new Callback()
        {
            @Override
            public void onResponse(Call call, final Response response)
            {
                if (response.isSuccessful())
                {
                    if (response.body().getStatus())
                    {
                        skillList = response.body().getSkillList();
                        ArrayAdapter 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 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.

提交回复
热议问题