如何获得我的折线图条目?

时间:2019-04-10 08:50:34

标签: java android web-services linechart

我正在尝试根据Web服务中的某些数据创建一个折线图。尽管我不确定是否为LineDataSet正确设置了所有数据。

所以我有一些数据列表,列表中的每个对象在Web服务中都有自己的ID。每当您按列表中的一个对象并按“显示图表”按钮(到目前为止,该按钮仅被称为“测试”,因为我尚未设置样式),它将启动一个新活动并在不同的地方运行Web服务ID的。该ID将与另一个网络服务调用进行比较,并从该Web服务调用中提取数据。来自新的webservice-call的数据应在图表中放置“日期”和“已满百分比”,并以“日期”为x轴。

使用“ dates”和“ percentFull”调用webservice没问题,我已经对其进行了测试,并且从中获取了所有正确的数据作为JsonArray。我将在下面发布相关代码。问题是,是否有人可以帮助我正确设置此设置,因为我显然做错了什么。

告诉我如果我需要提供更多信息,或者如果它太令人困惑,那么我仍然是一个非常年轻的开发人员。

public class ContainerListActivity extends AppCompatActivity...
{
// LISTS
    .....
    ArrayList<LineChartObject> lineChartObjectArrayList;
    ArrayList<Entry> containerFullEntry = new ArrayList<>();
    ArrayList<String> percentDatesList = new ArrayList<>();
}
 protected void onCreate(@Nullable Bundle savedInstanceState
{ 
    .....
    super.onCreate(savedInstanceState);
    getContianerGraph = new GetContianerGraph();
    lineChart = findViewById(R.id.lineChart);
    .....
}
public void onClick(View view) {
        hideSoftKeyboard(this);

        .....
        else if(view == testButton)
        {
            Intent intent = new Intent(this, ContainerGraphActivity.class);
            startActivity(intent);

            getContianerGraph.execute();
        }
}
//WEBSERVICE
public class GetContianerGraph extends AsyncTask<Void, Void, Void> {
        String error = "";
        JSONArray graphJsonArray;
        Helper helper = new Helper();
        private LineChartDataObject lineChartDataObject;

        @Override
        protected void onPreExecute()
        {
            lineChartObjectArrayList = new ArrayList<>();
        }

        //BACKGROUND WORK
        @Override
        protected Void doInBackground(Void... voids) {
            HttpURLConnection urlConn = null;


            try {
                //If token expires
                if (Calendar.getInstance(TimeZone.getTimeZone("GMT")).after(Helper.tokenDate(fileHelper.getPropertyFromSharedPreferences(getString(R.string.key_token_expires))))) {
                    LoginActivity.sessionExpired = true;
                    Helper.goToActivity(ContainerListActivity.this, LoginActivity.class);
                    return null;
                } else {

                    //String LeaseId = fileHelper.getPropertyFromSharedPreferences(getString(R.string.key_lease_id));



                    //Setup connection
                    URL url = new URL(getString(R.string.ws_get_container_graph)+String.valueOf(getSelectedContainerObject().getContId()));
                    urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.addRequestProperty("cache-control", "no-cache");
                    urlConn.addRequestProperty("Authorization", "Bearer " + fileHelper.getPropertyFromSharedPreferences(getString(R.string.key_token)));

                    //Read from webservice
                    BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                    br.close();

                    //Values from webservice
                    String jsonString = sb.toString();
                    graphJsonArray= new JSONArray(jsonString);

                    if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_CREATED &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_NOT_AUTHORITATIVE &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_NO_CONTENT &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_RESET &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_OK &&
                            urlConn.getResponseCode() != HttpURLConnection.HTTP_PARTIAL)
                    {
                        error = String.valueOf(urlConn.getRequestMethod());
                    }
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (urlConn != null) {
                    try {
                        urlConn.disconnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }



                for (LineChartObject lineChartObject : lineChartObjectArrayList) {
                    int i = lineChartObjectArrayList.indexOf(lineChartObject);

                    containerFullEntry.add(new Entry(i, lineChartObject.getPercentFull()));
                    Date date = Helper.parseWebserviceDateString(lineChartObject.getMesurementTime());
                    percentDatesList.add(Helper.formatDate(date, "dd-MM-yyy"));

                }

                runOnUiThread(() -> {

                    //dataset
                    LineDataSet percentageDataSet = new LineDataSet(containerFullEntry, "%");
                    percentageDataSet.setDrawCircles(false);
                    percentageDataSet.setColor(0xFF5989BD);
                    percentageDataSet.setDrawValues(false);
                    percentageDataSet.setLineWidth(2);
                    //create linedata
                    LineData lineData = new LineData();
                    lineData.addDataSet(percentageDataSet);

                    lineChartDataObject.setPercentFullDataSet(percentageDataSet);

                    //set line data
                    lineChartDataObject.getLineChart().setData(lineData);

                    //set x-axis formatter
                    XAxis xAxis = lineChartDataObject.getLineChart().getXAxis();
                    xAxis.setValueFormatter((value, axis) -> {
                        int index = Math.round(value);
                        return index < percentDatesList.size() ? percentDatesList.get(index) : "";
                    });
                    //set label count
                    xAxis.setLabelCount(3, true);

                    //Refresh LineChart
                    lineChartDataObject.getLineChart().invalidate();

                });
            }


            System.out.println("///////////////////////////////////////" + graphJsonArray);
            return null;
        }

        //After
        @Override
        protected void onPostExecute(Void aVoid) {
            if (error.equals("")) {
                try {
                    if (graphJsonArray != null) {
                        for (int i = 0; i < graphJsonArray.length(); i++) {
                            LineChartObject lco = new LineChartObject(graphJsonArray.getJSONObject(i).getString("MesurementTime"),
                                    graphJsonArray.getJSONObject(i).getInt("PercentFull"));
                            lineChartObjectArrayList.add(lco);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            super.onPostExecute(aVoid);
        }
    }
#ObjectClass for linechart:

public class LineChartDataObject {

    private View lineChartLayout;
    private LineChart lineChart;
    private LineDataSet percentFullDataSet;
    private Activity activity;

    public LineChartDataObject( Activity activity) {

        this.activity = activity;
    }

    //********************************************/
    // Linechart
    //********************************************/
    public void setPercentFullDataSet(LineDataSet percentFullDataSet)
    {
        this.percentFullDataSet = percentFullDataSet;
    }

    public LineDataSet getPercentFullDataSet()
    {
        return percentFullDataSet;
    }

    public LineChart getLineChart()
    {
        return lineChart;
    }

    public int getLineChartVisibility()
    {
        if(lineChart == null)

        {
            return View.GONE;
        }
        else
        {
            return lineChartLayout.getVisibility();
        }
    }

    //********************************************/
    // Setup linechart
    //********************************************/
    public void setLineChart(View resourceLineChart)
    {
        this.lineChartLayout = resourceLineChart;

        lineChart = resourceLineChart.findViewById(R.id.lineChart);
        lineChart.setExtraOffsets(5,0,5,0);
        lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
        lineChart.getLegend().setEnabled(false);
        lineChart.setHighlightPerDragEnabled(false);
        lineChart.setHighlightPerTapEnabled(false);
        lineChart.setDrawGridBackground(false);
        lineChart.getDescription().setEnabled(false);

        lineChart.setNoDataText(activity.getString(R.string.no_data_available));
        Paint p = lineChart.getPaint(Chart.PAINT_INFO);
        p.setColor(0xFF0A4EA3);
    }
}

因此,如上所述,我需要将Web服务中的数据设置到图表中,首先,它不会在图表中放入任何数据。

第二个:使用“测试”按钮返回上一个视图。我想我知道为什么,尽管我不确定如何解决这个问题,但在网络服务期间它会调用先前的视图。

最后,我正在努力将.execute正确放置,因此每隔两下我按下按钮就会使应用程序崩溃。

0 个答案:

没有答案