java - 上下文在 Fragment .onStart() 方法中不可用

标签 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. 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.lang.reflect.Method.invoke( native 方法)在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)在com.android.internal.os.ZygoteInit.main(ZygoteInit) .java:776)

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

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

最佳答案

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

关于java - 上下文在 Fragment .onStart() 方法中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023845/

相关文章:

Java - TableModelListeners 和 DataModelEvents

Android BLE Scan 永远找不到设备

php - 从 2 个表中检索数据 PHP、MySql、Android

Android AlertDialog异常 "Resources$NotFoundException"

java - 如何在 Spring Security 3.1 中使用 acl_entry 表中的 mask 字段?

java - 如何将 table%rowtype 的 oracle pl/sql out 参数引用为 java 中的对象

java - getSupportFragmentManager() 不适用于 fragment 类的 onCreateView() 方法。

java - 如何显示带边距或不同设计的 viewpager

java - 在 Java 中使用 Collectors 从两个 hashmaps 中返回一个平均 double

android - Visual Studio Enterprise 2015 RC Cordova Android 构建退出代码 1