首页 > 解决方案 > 上下文在 Fragment .onStart() 方法中不可用

问题描述

我在 Fragment 中使用 MPAndroidCharts,它允许我生成我想要显示的必要表格。MPAndroidCharts 库的一部分需要以下内容来初始化图表,我在 Fragment.onStart()方法中有此代码:

barColors.add(ContextCompat.getColor(getActivity().getApplicationContext(),R.color.bar_one));
barColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_two));
barColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_three));
barColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_four));
barColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_five));

每隔一段时间我就会收到以下错误,我不确定为什么,它不会在我每次打开托管片段的活动时发生,而是偶尔会发生。我相信片段的上下文尚未激活,但我无法确认:

java.lang.NullPointerException:尝试在 com.troychuinard.livevotingudacity.Fragment.PollFragment.updatePollResultAnswersDynamically(PollFragment.java:355 )在 com.troychuinard.livevotingudacity.Fragment.PollFragment.access$1300(PollFragment.java:63) 在 com.troychuinard.livevotingudacity.Fragment.PollFragment$3.onDataChange(PollFragment.java:304) 在 com.google.firebase.database。 obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.2:75) 在 com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0 .2:63) 在 com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.2:55) 在 android.os.Handler.handleCallback(Handler.java :751) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6119) 在 java。在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 的 lang.reflect.Method.invoke(Native Method) )

更新:请参阅下面的相关片段代码:

@Override
public void onStart() {
    super.onStart();
    valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            int numberOfPollAnswersAtIndexBelowDate = (int) dataSnapshot.child(ANSWERS_LABEL).getChildrenCount();
            updatePollResultAnswersDynamically(numberOfPollAnswersAtIndexBelowDate, dataSnapshot);

            //Simply displaying, no need for mutable transaction
            int voteCountTotal = 0;
            ArrayList<Long> pollAnswersTotals = new ArrayList<Long>();
            for (int x = 0; x < numberOfPollAnswersAtIndexBelowDate; x++) {
                pollAnswersTotals.add(x, (Long) dataSnapshot.child(ANSWERS_LABEL).child(String.valueOf(x + 1)).child(VOTE_COUNT_LABEL).getValue());
                voteCountTotal += pollAnswersTotals.get(x);
            }

            DecimalFormat formatter = new DecimalFormat("#,###,###");
            String totalFormattedVotes = formatter.format(voteCountTotal);
            mTotalVoteCounter.setText(getResources().getString(R.string.votes) + String.valueOf(totalFormattedVotes));

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    mSelectedPollRef.addValueEventListener(valueEventListener);

}

方法:

private void updatePollResultAnswersDynamically(int numberOfAnswers, DataSnapshot dataSnapshot) {

//        mPollResults.clearValues();

        pollResultChartValues = new ArrayList<BarEntry>();

        for (int i = 0; i < numberOfAnswers; i++) {
            Long chartLongResultvalue = (Long) dataSnapshot.child(ANSWERS_LABEL).child(String.valueOf(numberOfAnswers - i)).child(VOTE_COUNT_LABEL).getValue();
            float chartFloatResultvalue = chartLongResultvalue.floatValue();
            pollResultChartValues.add(new BarEntry(chartFloatResultvalue, i));
        }

        data = new BarDataSet(pollResultChartValues, "Poll Results");

//        data.setColors(new int[]{getResources().getColor(R.color.black)});
        //TODO: Check attachment to Activity; when adding a color, the getResources.getColor states
        //TODO: that the fragment was detached from the activity; potentially add this method to onCreateView() to avoid;
//        ArrayList<Integer> barColors = new ArrayList<>();
//        barColors.add(R.color.bar_one);
//        barColors.add(R.color.bar_two);
//        barColors.add(R.color.bar_three);
//        barColors.add(R.color.bar_four);
//        barColors.add(R.color.bar_five);

        mBarColors.clear();

        mBarColors.add(ContextCompat.getColor(getActivity().getApplicationContext(),R.color.bar_one));
        mBarColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_two));
        mBarColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_three));
        mBarColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_four));
        mBarColors.add(ContextCompat.getColor(getActivity().getApplicationContext(), R.color.bar_five));
        data.setColors(mBarColors);

        data.setAxisDependency(YAxis.AxisDependency.LEFT);
        MyDataValueFormatter f = new MyDataValueFormatter();
        data.setValueFormatter(f);


        //xAxis is a inverted yAxis since the graph is horizontal
        XAxis xAxis = mPollResults.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            xAxis.setTextSize(20);
        } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
            xAxis.setTextSize(16);
        }

        //yAxis is an inverted xAxis since the graph is horizontal
        YAxis yAxisLeft = mPollResults.getAxisLeft();
        yAxisLeft.setDrawGridLines(false);
        yAxisLeft.setEnabled(false);
        YAxis yAxisRight = mPollResults.getAxisRight();
        yAxisRight.setDrawGridLines(false);
        yAxisRight.setEnabled(false);


        Legend legend = mPollResults.getLegend();
        legend.setEnabled(false);


        //TODO: This figure needs to be dynamic and needs to adjust based on the number of users in the application
        //TODO: Or does it? Right now, it scales without it

        dataSets = new ArrayList<IBarDataSet>();

        dataSets.add(data);


        //Poll Answer Options get added here
        ArrayList<String> yVals = new ArrayList<String>();
        for (int x = 0; x < numberOfAnswers; x++) {
            String pollResult = (String) dataSnapshot.child(ANSWERS_LABEL).child(String.valueOf((numberOfAnswers) - x)).child("answer").getValue();
            yVals.add(x, pollResult);
        }

        BarData testBarData = new BarData(yVals, dataSets);
        //TODO: Fix all text sizes using this method
        if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
            testBarData.setValueTextSize(22);
        } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {
            testBarData.setValueTextSize(14);
        } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
            testBarData.setValueTextSize(12);
        } else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {
            testBarData.setValueTextSize(12);
        }

        mPollResults.getXAxis().setLabelRotationAngle(-15);
        mPollResults.getXAxis().setSpaceBetweenLabels(5);
        mPollResults.setTouchEnabled(false);
        mPollResults.setPinchZoom(false);
        mPollResults.setData(testBarData);
        data.notifyDataSetChanged();
        mPollResults.notifyDataSetChanged();
        mPollResults.invalidate();
    }

标签: javaandroidandroid-fragmentsandroid-contextmpandroidchart

解决方案


您正在处理两个彼此不了解的不同组件生命周期:

  1. 片段的生命周期并不总是附加上下文(活动)
  2. Firebase ValueEventListener 的生命周期,它与从您的数据库中读取相关联。

事物的编写方式,您的片段和您的 ValueEventListener 都不知道对方的生命周期。

有几种方法可以解决这个问题:

在 onStop 中删除您的 ValueEventListener

由于 onStart 发生在 onAttach 之后,而 onStop 发生在 onDetach 之前,您可以在 onStop 中删除 ValueEventListener。这样,您的听众注册将是对称的。当然,当您的片段与上下文分离时,您会错过 DataSnapshots。如果没问题,这可能会正常工作。

将应用程序上下文传递给 Fragment 构造函数

另一种方法是让您的 Fragment 在其构造函数中获取上下文,并将其保存在成员变量中并引用它而不是调用getActivity().

注意:如果您确实在构造函数中传递了 Context,请确保从传入的 Context 中获取应用程序上下文并引用它以避免泄漏活动上下文。你可以通过调用来做到这一点context.getApplicationContext();


推荐阅读