Java Android:从CSV文件中获取数据,并使用MPAndroidChart绘制折线图

Java Android:从CSV文件中获取数据,并使用MPAndroidChart绘制折线图,java,android,mpandroidchart,Java,Android,Mpandroidchart,在我的应用程序中,我使用MPAndroidchart,从CSV文件中获取数据并进行打印。此外,当通过添加更多数据更新CSV文件时,图表也应自动获取更新的数据并进行绘图 我的CSV如下所示: public class ChartActivity extends BaseAppCompatActivity { private Toolbar toolbar; private File logFile; @Override protected void onCrea

在我的应用程序中,我使用MPAndroidchart,从CSV文件中获取数据并进行打印。此外,当通过添加更多数据更新CSV文件时,图表也应自动获取更新的数据并进行绘图

我的CSV如下所示:

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);
       

    }
}
2020/11/11101:07,华氏92.6度

2020/11/15102:51,华氏96.9度

2020/11/15102:52,93.6华氏度

问题列表:

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);
       

    }
}
  • 在上面的数据中,虽然有日期/时间,但我只获取最后一列数据(温度数据)并绘制它与日期/时间的对比图(在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);
           
    
        }
    }
    
    公共类ChartActivity扩展了BaseAppCompatActivity{
    专用工具栏;
    私有文件日志文件;
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_图表);
    toolbar=(toolbar)findviewbyd(R.id.toolbar);
    设置支持操作栏(工具栏);
    ActionBar ActionBar=getSupportActionBar();
    if(actionBar!=null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    toolbar.setNavigationOnClickListener(新视图.OnClickListener(){
    @凌驾
    公共void onClick(视图){
    完成();
    }
    });
    }
    }
    恢复时公开作废(){
    super.onResume();
    日志文件=(文件)getIntent().getExtras().get(常量.EXTRA_日志文件);
    如果(日志文件!=null){
    setTitle(logFile.getName()+getString(R.string.charting));
    试一试{
    setLogText(日志文件);
    }catch(filenotfounde异常){
    e、 printStackTrace();
    }
    }
    }
    公共浮点解析浮点(字符串strNumber){
    if(strNumber!=null&&strNumber.length()>0){
    试一试{
    返回Float.parseFloat(strNumber);
    }捕获(例外e){
    return-1;//或用于标记此字段的某个值错误。或使函数先验证字段。。。
    }
    }
    否则返回0;
    }
    私有void setLogText(文件)引发FileNotFoundException{
    线形图=findViewById(R.id.chart1);
    //无描述文本
    chart.getDescription().setEnabled(false);
    //启用触摸手势
    chart.setTouchEnabled(真);
    图表.设定阻力减阻摩擦系数(0.9f);
    //启用缩放和拖动
    图表。setDragEnabled(真);
    图表.setScaleEnabled(真);
    chart.setDrawGridBackground(假);
    图表。setHighlightPerDragEnabled(真);
    //设置另一种背景色
    图表.背景颜色(颜色.白色);
    图表.设置视口偏移量(0f、0f、0f、0f);
    //获取图例(仅在设置数据后才可能)
    Legend l=chart.getLegend();
    l、 setEnabled(假);
    XAxis XAxis=chart.getXAxis();
    xAxis.setPosition(xAxis.XAxisPosition.TOP_内);
    设置字体(tfLight);
    xAxis.setTextSize(10f);
    xAxis.setTextColor(Color.WHITE);
    xAxis.setDrawAxisLine(false);
    xAxis.setDrawGridLines(真);
    setTextColor(Color.rgb(255,192,56));
    xAxis.setCenterAxisLabels(true);
    xAxis.setGranularity(0.5f);//一小时
    setValueFormatter(新的ValueFormatter(){
    private final SimpleDateFormat mFormat=新的SimpleDateFormat(“dd MMM HH:mm a”,Locale.ENGLISH);
    @凌驾
    公共字符串getFormattedValue(浮点值){
    long millis=时间单位.MINUTES.toMillis((长)值);
    返回格式(新日期(毫秒));
    }
    });
    YAxis leftAxis=chart.getAxisLeft();
    leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_图表);
    leftAxis.setTypeface(tfLight);
    leftAxis.setTextColor(ColorTemplate.getHoloBlue());
    leftAxis.setDrawGridLines(true);
    leftAxis.setGranularityEnabled(真);
    leftAxis.setaxis最小值(0f);
    设置轴最大值(170f);
    左轴设置偏移(-9f);
    leftAxis.setTextColor(Color.rgb(255,192,56));
    YAxis rightAxis=chart.getAxisRight();
    rightAxis.setEnabled(错误);
    ArrayList值=新的ArrayList();
    扫描仪输入流;
    inputStream=新扫描仪(文件);
    while(inputStream.hasNext()){
    String line=inputStream.next();
    
    如果(line.equals(“”){continue;}//请帮助我解决此问题。