在片段内查看null

时间:2018-04-06 11:11:36

标签: android android-fragments nullpointerexception butterknife

我这几个小时以来一直在努力。找不到任何理由。我不能在这里发布整个片段,但以下内容应该清楚。

@BindView(R.id.acService) AutoCompleteTextView autocompleteService;
@BindView(R.id.acAddress) AutoCompleteTextView autocompleteAddress;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    unbinder = ButterKnife.bind(this, view);

    initialize();
    loadSkillsData();

    return view;
}

private void initialize()
{
    context = getActivity();
    util = new Util(context);
    requestService = new RequestService();
    geoDataClient = Places.getGeoDataClient(context, null);

    autocompleteAdapter = new PlaceAutocompleteAdapter(context, geoDataClient, BOUNDS_ONTARIO, null);
    autocompleteAddress.setAdapter(autocompleteAdapter);

    mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    mapFragment.getMapAsync(this);
}

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

布局:XML

autocompleteService.setAdapter(skillAdapter); 一行中,我得到一个NPE,说我在空对象上调用setAdapter。调试告诉我此时autocompleteService确实为null。

为什么这个视图为空?在此之前,Butterknife.bind被称为方式。为什么视图没有初始化?

这是确切的错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                            at com.xyz.controllers.HomeFragment$3.onResponse(HomeFragment.java:183)
                                                            at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                            at android.os.Handler.handleCallback(Handler.java:739)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:148)
                                                            at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

3 个答案:

答案 0 :(得分:0)

覆盖onViewCreated并移动

executeAsync

进入那里

答案 1 :(得分:0)

在尝试改变视图之前,使用ViewTreeObserver.onGlobalLayoutListener确保视图已完全布局。以下是使用全局布局侦听器的loadSkillsData函数,它应解析您的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();
        }
    });
}

除了NPE的问题之外,您还将遇到使用领域的问题。 Realm需要在它自己的线程上访问,如果你从UI线程访问它会导致应用程序崩溃,就像你在上面的代码中那样。

答案 2 :(得分:0)

你必须在onCreateView方法中调用ButterKnife.bind

     // bind the view using butterknife
    ButterKnife.bind(this);