片段.onStart()方法中没有上下文

时间:2018-10-27 16:10:56

标签: java android android-fragments android-context mpandroidchart

我正在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));

每隔一段时间,我都会收到以下错误,并且我不确定为什么,每次打开承载Fragment的Activity时都不会发生这种情况,但是偶尔会发生一次。我相信Fragment的上下文尚未激活,但我无法确认:

java.lang.NullPointerException:尝试在com.troychuinard.livevotingudacity.Fragment.PollFragment.updatePollResultAnswersDynamically(PollFragment。)上的空对象引用上调用虚拟方法'android.content.Context android.content.ContextWrapper.getApplicationContext()'。 java:355)at com.troychuinard.livevotingudacity.Fragment.PollFragment.access $ 1300(PollFragment.java:63)at com.troychuinard.livevotingudacity.Fragment.PollFragment $ 3.onDataChange(PollFragment.java:304)at 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( android.os.Handler.dispatchMessage(Handler.java:95)处的Handler.java:751)android.app.ActivityThread.main(ActivityThread.jav)处的android.os.Looper.loop(Looper.java:154)处的Handler.java:751) a:6119),位于com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)的java.lang.reflect.Method.invoke(本机方法)。 main(ZygoteInit.java:776)

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

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

2 个答案:

答案 0 :(得分:1)

您应将所有基于上下文的初始化移至onAttach(Context context)方法。片段必须先附加到上下文,然后才能使用getActivity()方法。否则,该方法将返回null。

答案 1 :(得分:1)

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

  1. 并非始终具有附加上下文(活动)的lifecycle of your fragment
  2. Firebase ValueEventListener的生命周期,该生命周期与从数据库中读取数据有关。

编写方式,您的片段和ValueEventListener都不了解对方的生命周期。

您可以通过以下两种方式解决此问题:

在onStop中删除ValueEventListener

由于onStart发生在onAttach之后,而onStop发生在onDetach之前,因此您可以在onStop中删除ValueEventListener。这样,您的侦听器注册将是对称的。当然,当您的片段与上下文分离时,您将错过DataSnapshots。如果可以,这可能会很好。

将应用程序上下文传递给您的Fragment构造器

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

注意:如果确实在构造函数中传递了Context,请确保从传递的Context中获取应用程序上下文,并引用该上下文以避免泄漏活动上下文。您可以致电context.getApplicationContext();