okhttp和linechart的应用:从http获取数据生成折线图 34 / 100

MainActivity类

package com.example.linecharthttp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private final OkHttpClient okHttpClient = new OkHttpClient();
    private Button mGetNumberButton;
    private Button mGetDataButton;
    private LineChart mLineChart;
    private List<Entry> mListOne = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLineChart = findViewById(R.id.lineChart);
        mGetNumberButton = findViewById(R.id.getNumberButton);
        mGetNumberButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GetNumber();

            }
        });

        mGetDataButton = findViewById(R.id.getDataButton);
        mGetDataButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doGetAsync();
            }
        });

    }

    public int GetNumber() {
        Request request = new Request.Builder()
                .url("http://192.xxx.x.x:xxxx/PlotData/Size")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                String[] dataBuf_FirstLine = string.split(",");
                String[] Datasize = dataBuf_FirstLine[0].split(":");
                String size = Datasize[1];
                Log.e(TAG, "数据长度为:" + size);
            }
        });
        return 0;
    }

    public void doGetAsync() {
        Request request = new Request.Builder()
                .url("http://192.xxx.x.x:xxxx/PlotData/P1")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String string = response.body().string();
                String[] dataBuf_FirstLine = string.split("\":");
                String[] volt = dataBuf_FirstLine[4].split(",");
                volt[10] = "3.892264";
                volt[0] = "3.892206";

                ArrayList listone = new ArrayList<>(volt.length);
                Collections.addAll(listone, volt);
                listone.remove(1);
                listone.remove(10);//上面删除一个,最后一个就是第10个

                String[] date = dataBuf_FirstLine[2].split(",");
                date[0] = "00:00:00:020";
                date[9] = "00:00:00:920";
                ArrayList listtow = new ArrayList<>(date.length);
                Collections.addAll(listtow, date);
                listtow.remove(10);
                TextData textData = new TextData();

                for (int i = 0; i < listtow.size(); i++) {
                    String strDateTime = (String) listtow.get(i);
                    String strValue1 = (String) listone.get(i);
                    textData.setTestDateTime(strDateTime);
                    textData.setVolt(Double.parseDouble(strValue1));
                    mListOne.add(new Entry(i, (float) textData.getVolt()));
                }

                initChart();
                initChartBackground();


                Log.e(TAG, listone.toString());
            }
        });
    }

    private void initChartBackground() {
        Description description = null;
        //设置描述
        description = new Description();
        description.setEnabled(true);//设置是否启用标题
        description.setText("测试时间-电压-电流曲线");//设置标题文本
        description.setTextSize(20);//设置文本大小
        description.setTypeface(Typeface.MONOSPACE);//设置文本字体样式
        description.setTextColor(Color.BLACK);//设置文本颜色
        description.setXOffset(10f);//设置X轴的偏移量,float值
        description.setYOffset(10f);//设置Y轴的偏移量,float值
        //mLineChart.setBackgroundColor(Color.BLACK);
        // description.setTextAlign(Paint.Align.CENTER);//提示框的文本对齐,中心对齐
        description.setPosition(350, 30);//设置描述所处的位置
        mLineChart.setDescription(description);//添加给LineChart
        // mLineChart.setNoDataText("暂无数据");   // 没有数据时样式

        XAxis xAxis = mLineChart.getXAxis();//得到x轴
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的位置,在整个图形的底部

        xAxis.setLabelCount(mListOne.size(), true); //设置X轴刻度 第一个参数是想要x轴有多少条刻度,第二个参数true是将刻度数设置为你的第一个参数的数量 ,false是将刻度数设置为你的第一个参数的数量+1(0.0点也要算哦)
        xAxis.setGranularity(1f);//设置x轴坐标间的最小间距
        xAxis.setAxisMaximum(mListOne.size() + 1);//设置x轴的最大范围
        // xAxis.setAxisMinimum(0f);//设置x轴的最小范围
        //xAxis.setGridColor(Color.TRANSPARENT);//设置x轴刻度透明

        //Y轴不是有左右两边嘛,这就是获取左右两边的y轴

        YAxis axisLeft = mLineChart.getAxisLeft();
        //    axisRight.setEnabled(false);//将右边的y轴隐藏
        //y轴最大值最小值范围
        //  axisLeft.setAxisMaximum(550f);
        //axisLeft.setAxisMinimum(0f);

        axisLeft.setTextColor(Color.parseColor("#000000"));//设置左y轴字的颜色
        axisLeft.setAxisLineColor(Color.BLACK);//y轴颜色
        axisLeft.setGridColor(Color.parseColor("#C0C0C0"));//y轴线颜色
        axisLeft.enableGridDashedLine(10f, 10f, 0f);

    }

    private void initChart() {
        LineDataSet one = new LineDataSet(mListOne, "电压");//将数据赋值到你的线条上
        one.setColor(Color.parseColor("#67BCFF"));//设置线的颜色
        one.setDrawCircles(false);//设置是否绘制点,默认是true
        one.setDrawValues(false);//是否绘制点上的文字,默认为true
        LineData lineData = new LineData();// //线的总管理
        lineData.addDataSet(one);//每加一条就add一次
        mLineChart.setData(lineData);//把线条设置给你的lineChart上
        mLineChart.invalidate();//刷新
    }
}

TextData类

package com.example.linecharthttp;

public class TextData {
    String mTestDateTime;   // 测试记录点日期时间
    double mVolt;           // 电压(double)

    public TextData() {
    }

    public String getTestDateTime() {
        return mTestDateTime;
    }

    public void setTestDateTime(String testDateTime) {
        mTestDateTime = testDateTime;
    }

    public double getVolt() {
        return mVolt;
    }

    public void setVolt(double volt) {
        mVolt = volt;
    }

    public TextData(String testDateTime, double volt) {
        mTestDateTime = testDateTime;
        mVolt = volt;
    }

    @Override
    public String toString() {
        return "测试时间-电压曲线数据:" +
                "测试时间为:" + mTestDateTime + '\'' +
                ", 测试电压为:" + mVolt +
                '}';
    }
}

activity

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/lineChart"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        tools:ignore="MissingClass">

    </com.github.mikephil.charting.charts.LineChart>

    <Button
        android:id="@+id/getNumberButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取数量"
        android:layout_marginTop="50dp"/>

    <Button
        android:id="@+id/getDataButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="获取数据并生成曲线"
        android:layout_marginTop="30dp"/>

</LinearLayout>

效果
okhttp和linechart的应用:从http获取数据生成折线图 34 / 100_第1张图片

需要加的依赖

这个没有依据,都是我自己会用到的,具体加那些看自己代码需要

    implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
    def dialogx_version = "0.0.46"
    implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
    implementation 'androidx.sqlite:sqlite:2.2.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.7'
    implementation 'com.alibaba:fastjson:1.2.67'
    implementation("com.squareup.okhttp3:okhttp:4.10.0")

AndroidManifest.xml

也是按我自己需要的添加

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application

        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.LineChartHttp"
        android:usesCleartextTraffic="true"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

最后
okhttp和linechart的应用:从http获取数据生成折线图 34 / 100_第2张图片

你可能感兴趣的:(okhttp,http,网络协议)