如何在片段中的getActivity中修复nullpointer expecption?

时间:2018-03-15 04:54:09

标签: java android android-studio mpandroidchart

我正在使用MPAndroidChart解析条形图中的json数据,同时在第一次运行程序运行perfeclty时运行程序但是如果我再次在同一个碎片应用程序中崩溃,而搜索我知道因为getActivity null指针运行任何suggetion如何解决它。我的代码是。

final RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    final JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            final List<BarEntry> yEntrys = new ArrayList<>();
            Log.d(TAG, response.toString());
            Gson gson = new Gson();
            SiteStatistics siteStatistics = gson.fromJson(response.toString(), SiteStatistics.class);
            try {

                String activitiesCount = siteStatistics.getActivitiesSeen();
                String theftsCount = siteStatistics.getTheftsAverted();
                String arrestsCount = siteStatistics.getArrests();
                String alaramsCount = siteStatistics.getOutputs();
                String missedCount = siteStatistics.getMissed();
                yEntrys.add(new BarEntry(0f, Integer.parseInt(activitiesCount)));
                yEntrys.add(new BarEntry(1f, Integer.parseInt(theftsCount)));
                yEntrys.add(new BarEntry(2f, Integer.parseInt(arrestsCount)));
                yEntrys.add(new BarEntry(3f, Integer.parseInt(alaramsCount)));
                yEntrys.add(new BarEntry(4f, Integer.parseInt(missedCount)));


            } catch (Exception e) {
                e.getMessage();
            }

            /*BarDataSet set1;

            if (mChart.getData() != null &&
                    mChart.getData().getDataSetCount() > 0) {
                set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                set1.setValues(yVals1);
                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();
                mChart.invalidate();
            } else {
                set1 = new BarDataSet(yVals1, "The year 2017");

                set1.setDrawIcons(false);

                set1.setColors(ColorTemplate.MATERIAL_COLORS);

                ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
                dataSets.add(set1);

                BarData data = new BarData(dataSets);
                data.setValueTextSize(10f);

                data.setBarWidth(0.9f);

                mChart.setData(data);*/
            BarDataSet set1;

            set1 = new BarDataSet(yEntrys,"");
            set1.setBarBorderWidth(1f);
            set1.setDrawIcons(false);
            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            ArrayList<Integer> colors = new ArrayList<Integer>();
            colors.add(ContextCompat.getColor(getActivity(),android.R.color.holo_blue_bright));
            colors.add(ContextCompat.getColor(getActivity(),android.R.color.holo_purple));
            colors.add(ContextCompat.getColor(getActivity(),android.R.color.holo_green_dark));
            colors.add(ContextCompat.getColor(getActivity(),android.R.color.holo_red_dark));
            colors.add(ContextCompat.getColor(getActivity(),android.R.color.holo_orange_light));

            set1.setColors(colors);
            //set1.setColors(ColorTemplate.VORDIPLOM_COLORS);
            /*set1.setColors(new int[]
                    {
                            R.color.activities, R.color.theft_averted, R.color.missed,
                            R.color.armed_activated, R.color.arrests
                    }, getActivity());*/
            mChart.setExtraBottomOffset(0);
            BarData data = new BarData(dataSets);
            data.setBarWidth(0.9f);
            data.setValueFormatter(new MyValueFormatter());

            XAxis xAxis =  mChart.getXAxis();
            //IAxisValueFormatter xAxisFormatter = new MyXAxisValueFormatter(mChart);
            //xAxis.setValueFormatter(xAxisFormatter);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setLabelRotationAngle(30);
            xAxis.setSpaceMax(5f);
            xAxis.setGranularity(1f);
            xAxis.setLabelCount(5);
            xAxis.setDrawGridLines(false);
            xAxis.setGranularityEnabled(true);
            Legend l= mChart.getLegend();

            l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            l.setDrawInside(false);
            l.setForm(Legend.LegendForm.SQUARE);
            l.setFormSize(9f);
            l.setTextSize(11f);
            l.setXEntrySpace(4f);


            LegendEntry l1=new LegendEntry("Activities", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getActivity(),android.R.color.holo_blue_bright));
            LegendEntry l2=new LegendEntry("ArmedActivated", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getActivity(),android.R.color.holo_purple));
            LegendEntry l3=new LegendEntry("Theft Averted", Legend.LegendForm.DEFAULT,10f,1f,null,ContextCompat.getColor(getActivity(),android.R.color.holo_green_dark));
            LegendEntry l4=new LegendEntry("Arrest", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getActivity(),android.R.color.holo_red_dark));
            LegendEntry l5=new LegendEntry("Missed", Legend.LegendForm.DEFAULT,10f,2f,null, ContextCompat.getColor(getActivity(),android.R.color.holo_orange_light));
            mChart.setFitBars(true);
            l.setEnabled(true);
            l.setWordWrapEnabled(true);
            l.setCustom(new LegendEntry[]{l1,l2,l3,l4,l5});
            mChart.setData(data);
            mChart.invalidate();

            }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();

        }
    });
    requestQueue.add(jsonObjectRequest);

我的日志是。

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.getColor(int)' on a null object reference
                                                               at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:409)
                                                               at com.ivigil.ivis.fragments.CurrentFragment$1.onResponse(CurrentFragment.java:214)
                                                               at com.ivigil.ivis.fragments.CurrentFragment$1.onResponse(CurrentFragment.java:155)
                                                               at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:83)
                                                               at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:106)
                                                               at android.os.Handler.handleCallback(Handler.java:789)
                                                               at android.os.Handler.dispatchMessage(Handler.java:98)
                                                               at android.os.Looper.loop(Looper.java:164)
                                                               at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

0 个答案:

没有答案