android:从csv文件中获取数据,并使用mpandroidchart绘制折线图

kcugc4gi  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(312)

在我的应用程序中,我使用mpandroidchart,从csv文件中获取数据并打印出来。此外,当csv文件通过添加更多数据进行更新时,图表也应自动获取更新的数据并进行打印。
我的csv如下所示:
2020/11/11,上午01:07,92.6°f
2020/11/15,下午02:51,96.9°f
2020/11/15,下午02:52,93.6°f
问题列表:
在上面的数据中,虽然有日期/时间,但我只获取最后一列数据(温度数据)并绘制它与日期/时间的对比图(在mpandroidchart x轴格式化程序中)。但在我的例子中,图表是空的,x轴没有显示。
接下来,如果我想直接从csv文件中获取日期/时间(字符串数据类型)和温度数据并绘制x轴的格式,添加系列,在图表上设置数据并使用mpandroidchart绘制?
这是我的密码:

public class ChartActivity extends BaseAppCompatActivity {

    private Toolbar toolbar;
    private File logFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
}

  public void onResume() {
        super.onResume();

        logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
        if (logFile != null) {
            toolbar.setTitle(logFile.getName() + getString(R.string.charting));

              try {
                setLogText(logFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    public float Parsefloat(String strNumber) {
        if (strNumber != null && strNumber.length() > 0) {
            try {
                return Float.parseFloat(strNumber);
            } catch(Exception e) {
                return -1;   // or some value to mark this field is wrong. or make a function validates field first ...
            }
        }
        else return 0;
    }

    private void setLogText(File file) throws FileNotFoundException {

      LineChart chart = findViewById(R.id.chart1);

        // no description text
        chart.getDescription().setEnabled(false);

        // enable touch gestures
        chart.setTouchEnabled(true);

        chart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setHighlightPerDragEnabled(true);

        // set an alternative background color
        chart.setBackgroundColor(Color.WHITE);
        chart.setViewPortOffsets(0f, 0f, 0f, 0f);

         // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        l.setEnabled(false);

        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.TOP_INSIDE);
        xAxis.setTypeface(tfLight);
        xAxis.setTextSize(10f);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(true);
        xAxis.setTextColor(Color.rgb(255, 192, 56));
        xAxis.setCenterAxisLabels(true);
        xAxis.setGranularity(0.5f); // one hour
        xAxis.setValueFormatter(new ValueFormatter() {

            private final SimpleDateFormat mFormat = new SimpleDateFormat("dd MMM HH:mm a", Locale.ENGLISH);

            @Override
            public String getFormattedValue(float value) {

                long millis = TimeUnit.MINUTES.toMillis((long) value);
                return mFormat.format(new Date(millis));
            }
        });

        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        leftAxis.setTypeface(tfLight);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setAxisMaximum(170f);
        leftAxis.setYOffset(-9f);
        leftAxis.setTextColor(Color.rgb(255, 192, 56));

        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);

        ArrayList<Entry> values = new ArrayList<>();

        Scanner inputStream;

        inputStream = new Scanner(file);

        while(inputStream.hasNext()){
            String line= inputStream.next();

            if (line.equals("")) { continue; } // <--- notice this line

            String[] values = line.split(",");
            String V = values[0];  // Date
            String W= values[1];   // Time (12 hours format)
            String X= values[2];   // Temperature

            String display = X;

            if(!TextUtils.isEmpty(display)) {
                display  = display.substring(0, display.length()-2);

                X = display;
            }

            float T = Parsefloat(X); // converts string temperature to float value

              long now = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
              double to = now;
              values.add(new Entry((float) to, T));

         }

        inputStream.close();

         // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(values, "DataSet 1");
        set1.setAxisDependency(AxisDependency.LEFT);
        set1.setColor(ColorTemplate.getHoloBlue());
        set1.setValueTextColor(ColorTemplate.getHoloBlue());
        set1.setLineWidth(1.5f);
        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setFillAlpha(65);
        set1.setFillColor(ColorTemplate.getHoloBlue());
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        set1.setDrawCircleHole(false);

        // create a data object with the data sets
        LineData data = new LineData(set1);
        data.setValueTextColor(Color.WHITE);
        data.setValueTextSize(9f);

        // set data
        chart.setData(data);

    }
}

我需要一个类似的图表如下:
图表示例图
请帮帮我。谢谢您!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题