Android/Java 创建辅助类来创建图表

2024-05-16

Goal:

创建用于图形生成的辅助类

背景:

我有 3 个片段,每个片段收集一些传感器数据(加速度计、陀螺仪、旋转)并使用 GraphView 绘制图表。以下是其中一个片段的代码(该代码当前工作正常):

public class GyroscopeFragment extends Fragment implements SensorEventListener {

    private final short TYPE_GYROSCOPE = Sensor.TYPE_GYROSCOPE;
    private final short POLL_FREQUENCY = 100; //in milliseconds
    private final short MAX_POINTS_DISPLAYED = 50;
    private SensorManager sensorManager;
    private Sensor sensor;
    private Sensor gyroscope;
    private long lastUpdate = -1;

    float curGyroX;
    float curGyroY;
    float curGyroZ;

    private LineGraphSeries<DataPoint> gyroXSeries;
    private LineGraphSeries<DataPoint> gyroYSeries;
    private LineGraphSeries<DataPoint> gyroZSeries;
    private double graphXTime = 1d;

    public GyroscopeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_gyroscope, container, false);

        //Set the nav drawer item highlight
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.navigationView.setCheckedItem(R.id.nav_gyroscope);

        //Set actionbar title
        mainActivity.setTitle("Gyroscope");

        //Sensor manager
        sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        gyroscope = (Sensor) sensorManager.getDefaultSensor(TYPE_GYROSCOPE);

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST);

        //Create graph
        GraphView gyroGraph = (GraphView) getView().findViewById(R.id.gyroGraph);

        gyroGraph.getLegendRenderer().setVisible(true);
        gyroGraph.getLegendRenderer().setFixedPosition(0,0);

        gyroGraph.getGridLabelRenderer().setHighlightZeroLines(false);

        gyroXSeries = new LineGraphSeries<DataPoint>();
        gyroYSeries = new LineGraphSeries<DataPoint>();
        gyroZSeries = new LineGraphSeries<DataPoint>();

        gyroXSeries.setTitle("X");
        gyroYSeries.setTitle("Y");
        gyroZSeries.setTitle("Z");

        gyroXSeries.setColor(Color.RED);
        gyroYSeries.setColor(Color.GREEN);
        gyroZSeries.setColor(Color.BLUE);

        gyroGraph.addSeries(gyroXSeries);
        gyroGraph.addSeries(gyroYSeries);
        gyroGraph.addSeries(gyroZSeries);

        gyroGraph.getViewport().setYAxisBoundsManual(true);
        gyroGraph.getViewport().setMinY(-10);
        gyroGraph.getViewport().setMaxY(10);

        gyroGraph.getViewport().setXAxisBoundsManual(true);
        gyroGraph.getViewport().setMinX(0);
        gyroGraph.getViewport().setMaxX(MAX_POINTS_DISPLAYED);
    }

    @Override
    public void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        sensor = event.sensor;

        curGyroX = event.values[0];
        curGyroY = event.values[1];
        curGyroZ = event.values[2];

        long curTime = System.currentTimeMillis();
        long diffTime = (curTime - lastUpdate);

        // only allow one update every POLL_FREQUENCY.
        if (diffTime > POLL_FREQUENCY) {
            lastUpdate = curTime;

            graphXTime += 1d;
            gyroXSeries.appendData(new DataPoint(graphXTime, curGyroX), true, MAX_POINTS_DISPLAYED);
            gyroYSeries.appendData(new DataPoint(graphXTime, curGyroY), true, MAX_POINTS_DISPLAYED);
            gyroZSeries.appendData(new DataPoint(graphXTime, curGyroZ), true, MAX_POINTS_DISPLAYED);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //Safe not to implement
    }
}

我发现在这 3 个片段中我重复了很多图形生成代码onResume所以我想创建一个 GraphHelper 类,我可以实例化它来创建图形,其优点是如果我想改变图形的外观,只需在一处更改代码。然而,我对 Java 很陌生,因此在创建这个新类时遇到了困难。

尝试的解决方案:

我设法提出以下课程来尝试解决该问题:

public class GraphHelper {

    private final GraphView graph;
    private final LineGraphSeries<DataPoint> xSeries;
    private final LineGraphSeries<DataPoint> ySeries;
    private final LineGraphSeries<DataPoint> zSeries;

    public GraphHelper(GraphView graph, LineGraphSeries<DataPoint> xSeries,
                            LineGraphSeries<DataPoint> ySeries, LineGraphSeries<DataPoint> zSeries, short maxDisplayed){
        this.graph = graph;
        this.xSeries = xSeries;
        this.ySeries = ySeries;
        this.zSeries = zSeries;

        graph.getLegendRenderer().setVisible(true);
        graph.getLegendRenderer().setFixedPosition(0, 0);

        graph.getGridLabelRenderer().setHighlightZeroLines(false);

        xSeries = new LineGraphSeries<DataPoint>();
        ySeries = new LineGraphSeries<DataPoint>();
        zSeries = new LineGraphSeries<DataPoint>();

        xSeries.setTitle("X");
        ySeries.setTitle("Y");
        zSeries.setTitle("Z");

        xSeries.setColor(Color.RED);
        ySeries.setColor(Color.GREEN);
        zSeries.setColor(Color.BLUE);

        graph.addSeries(xSeries);
        graph.addSeries(ySeries);
        graph.addSeries(zSeries);

        graph.getViewport().setYAxisBoundsManual(true);
        graph.getViewport().setMinY(-10);
        graph.getViewport().setMaxY(10);

        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(maxDisplayed);
    }
}

并改变了我的片段onResume看起来像这样(其他一切都一样):

@Override
public void onResume() {
    super.onResume();
    sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST);

    //Create graph
    GraphView gyroGraph = (GraphView) getView().findViewById(R.id.gyroGraph);

    new GraphHelper(gyroGraph, gyroXSeries, gyroYSeries, gyroZSeries, MAX_POINTS_DISPLAYED);
}

问题#1:

每当我尝试查看图形片段时,都会收到以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jjoe64.graphview.series.LineGraphSeries.appendData(com.jjoe64.graphview.series.DataPointInterface, boolean, int)' on a null object reference

这是指onSensorChanged我试图将数据附加到该系列的方法。似乎不知道什么gyroXSeries是因为我将其添加到助手中的图表中。

问题#2:

目前我声明gyroXSeries在主片段类以及辅助类的顶部,并创建一个新的LineGraphSeries辅助构造函数中的对象。有没有办法减少这段代码的重复呢?

EDIT

为了响应下面的评论,我进行了以下更改,新的 GraphHelper 类如下所示:

public class GraphHelper {

    private final GraphView graph;
    private final LineGraphSeries<DataPoint> xSeries;
    private final LineGraphSeries<DataPoint> ySeries;
    private final LineGraphSeries<DataPoint> zSeries;


    public GraphHelper(GraphView graph, LineGraphSeries<DataPoint> xSeries,
                            LineGraphSeries<DataPoint> ySeries, LineGraphSeries<DataPoint> zSeries, short maxDisplayed){
        this.graph = graph;
        this.xSeries = xSeries;
        this.ySeries = ySeries;
        this.zSeries = zSeries;

        graph.getLegendRenderer().setVisible(true);
        graph.getLegendRenderer().setFixedPosition(0, 0);

        graph.getGridLabelRenderer().setHighlightZeroLines(false);

        xSeries.setTitle("X");
        ySeries.setTitle("Y");
        zSeries.setTitle("Z");

        xSeries.setColor(Color.RED);
        ySeries.setColor(Color.GREEN);
        zSeries.setColor(Color.BLUE);

        graph.addSeries(xSeries);
        graph.addSeries(ySeries);
        graph.addSeries(zSeries);

        graph.getViewport().setYAxisBoundsManual(true);
        graph.getViewport().setMinY(-10);
        graph.getViewport().setMaxY(10);

        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(maxDisplayed);
    }
}

陀螺仪片段与原来相同,变化为onResume我上面做的

这会导致以下错误:

致命异常:主要 进程:net.binarysea.sensorload,PID:25997 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void com.jjoe64.graphview.series.LineGraphSeries.setTitle(java.lang.String)” 在net.binarysea.sensorload.GraphHelper。(GraphHelper.java:30) 在net.binarysea.sensorload.GyrscopeFragment.onResume(GyrscopeFragment.java:73) 在 android.support.v4.app.Fragment.performResume(Fragment.java:2005) 在 android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) 在 android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) 在 android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 在 android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) 在 android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 在 android.os.Handler.handleCallback(Handler.java:739) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


将您的图形助手类更改为此。

public class GraphHelper {
    public GraphHelper(GraphView graph, LineGraphSeries<DataPoint> xSeries,
                   LineGraphSeries<DataPoint> ySeries, LineGraphSeries<DataPoint> zSeries, short maxDisplayed){

    graph.getLegendRenderer().setVisible(true);
    graph.getLegendRenderer().setFixedPosition(0, 0);

    graph.getGridLabelRenderer().setHighlightZeroLines(false);

    xSeries.setTitle("X");
    ySeries.setTitle("Y");
    zSeries.setTitle("Z");

    xSeries.setColor(Color.RED);
    ySeries.setColor(Color.GREEN);
    zSeries.setColor(Color.BLUE);

    graph.addSeries(xSeries);
    graph.addSeries(ySeries);
    graph.addSeries(zSeries);

    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMinY(-10);
    graph.getViewport().setMaxY(10);

    graph.getViewport().setXAxisBoundsManual(true);
    graph.getViewport().setMinX(0);
    graph.getViewport().setMaxX(maxDisplayed);
    }
}

像这样称呼它:

@Override
public void onResume() {
    super.onResume();
    sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST);

    //Create graph
    GraphView gyroGraph = (GraphView) getView().findViewById(R.id.gyroGraph);

    gyroXSeries = new LineGraphSeries<DataPoint>();
    gyroYSeries = new LineGraphSeries<DataPoint>();
    gyroZSeries = new LineGraphSeries<DataPoint>();

    new GraphHelper(gyroGraph, gyroXSeries, gyroYSeries, gyroZSeries, MAX_POINTS_DISPLAYED);
}

这也是在java中做助手的更合适的方法:

public class GraphHelper {

public GraphHelper() { }

public static void initializeGraph(GraphView graph, LineGraphSeries<DataPoint> xSeries,
                                   LineGraphSeries<DataPoint> ySeries, LineGraphSeries<DataPoint> zSeries, short maxDisplayed){
    graph.getLegendRenderer().setVisible(true);
    graph.getLegendRenderer().setFixedPosition(0, 0);

    graph.getGridLabelRenderer().setHighlightZeroLines(false);

    xSeries.setTitle("X");
    ySeries.setTitle("Y");
    zSeries.setTitle("Z");

    xSeries.setColor(Color.RED);
    ySeries.setColor(Color.GREEN);
    zSeries.setColor(Color.BLUE);

    graph.addSeries(xSeries);
    graph.addSeries(ySeries);
    graph.addSeries(zSeries);

    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMinY(-10);
    graph.getViewport().setMaxY(10);

    graph.getViewport().setXAxisBoundsManual(true);
    graph.getViewport().setMinX(0);
    graph.getViewport().setMaxX(maxDisplayed);
}
}

这样你就没有等待垃圾收集的随机对象。 要调用它,请使用:

GraphHelper.initializeGraph(...)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android/Java 创建辅助类来创建图表 的相关文章

随机推荐

  • 在具有子项的“contenteditable”div 中设置插入符位置

    我有一个这样的 HTML 结构 div This is some plain boring content div 我还有这个函数 允许我将插入符位置设置到 div 中我想要的任何位置 Move caret to a specific po
  • asp.net MVC4 中的条件验证

    我希望能够根据从哪个控制器调用视图来启动一些验证函数 我将在 ViewState 或其他内容中设置一个变量 这将帮助我知道从哪个控制器调用该视图 换句话说 如果设置了某个变量 我希望需要验证 这是当我将 Jquery 放入代码中时我在 MV
  • 如何定位整个 JSF 页面被 p:blockUI / pe:blockUI 阻止?

    该示例演示了阻塞
  • 在 Laravel 中按数据透视表 create_at 排序

    在我的数据库中 我有以下表格 courses id 名称 创建时间 更新时间 students id 名称 创建时间 更新时间 课程 学生 id course id student id created at updated at 我正在尝
  • 不支持 URI 前缀

    我正在尝试使用以下方法加载和播放波形文件 SoundPlayer simpleSound new SoundPlayer pack application MyAssembly component Sounds 10meters wav s
  • VS2010中如何切换头文件和实现?

    Visual Studio 2010 中是否有允许在标头 C C h 文件 和实现 C C cpp 文件 之间切换的键盘快捷键或免费插件 MS added this feature in Visual Studio 2013 It s a
  • 删除匹配前的一个单词和一个单词

    匹配之前的一个单词可以是一组任何符号 例如 D E F 我有一个正则表达式 s w s XXX 输入示例 This is KKK M D D xXx PPP输出示例 This is KKK PPP 所以我需要删除 XXX 之前的 1 个单词
  • 提升变量有目的吗?

    我最近学习了很多 JavaScript 并且一直在尝试理解提升变量的值 如果有的话 我 现在 明白JS是一个两遍系统 它编译然后执行 另外 我知道 var 关键字 存在 在它声明的词法范围中 因此如果在引擎为其赋值之前调用它 那么它是 未定
  • RStudio 不会通过 rPython 调用加载所有 Python 模块

    我从 Bash 和 RStudio 中运行相同的脚本时出现一些意外行为 请考虑以下事项 我有一个文件夹 rpython 包含两个脚本 test1 R library rPython setwd rpython python load tes
  • 如何确定与视频中物体的距离?

    我有一个从行驶中的车辆前面录制的视频文件 我将使用 OpenCV 进行对象检测和识别 但我停留在一方面 如何确定距已识别物体的距离 我可以知道我当前的速度和现实世界的 GPS 位置 但仅此而已 我无法对我正在跟踪的对象做出任何假设 我计划用
  • 如何通过 C API 在自己的环境中执行不受信任的 Lua 文件

    我想通过调用在其自己的环境中执行不受信任的 lua 文件lua setfenv http pgl yoyo org luai i lua setfenv这样它就不会影响我的任何代码 该函数的文档仅解释了如何调用函数 而不解释如何执行文件 目
  • (AD) ldap 领域中的组成员资格

    我在 java ee 企业应用程序中使用 JAAS 框架进行身份验证和授权过程 我使用 GlassFish 作为应用程序服务器 我的领域配置如下所示
  • CSS 未在 Django 项目中加载?

    我是 Django 新手 但负责该项目的前端工作 我一直在研究如何准确加载 css 文件 但我发现这些方法不起作用 这是 html 文件布局 load static
  • 迁移到 Jakarta EE:无法找到 URI 的 taglib [c]:[jakarta.tags.core] [重复]

    这个问题在这里已经有答案了 我尝试从 Spring 5 升级到 Spring 6 并收到以下错误 Unable to find taglib c for URI jakarta tags core 我的 pom 中有以下内容
  • Internet Explore 8 不会使用 .attr() 更改图像 src

    我设置了一个页面 当用户用鼠标或触控板滚动时 该页面将快速浏览一系列图像 我使用 jQuery 来测量距页面顶部的距离 scrollTop 然后更改 DOM 中特定 id 的图像源 这在 Firefox Chrome Safari Oper
  • 优化 LATERAL join 中的慢速聚合

    在我的 PostgreSQL 9 6 2 数据库中 我有一个查询 该查询根据一些股票数据构建计算字段表 它为表中的每一行计算 1 到 10 年的移动平均窗口 并将其用于周期性调整 具体来说 CAPE CAPB CAPC CAPS 和 CAP
  • 谷歌地图url如何定义圆形标记?

    我想打开默认地图应用程序 但我想要一个圆形标记 而不是默认标记 这就是我所拥有的 case Device Android if string IsNullOrEmpty imovel Endereco Freguesia uri new U
  • pip/easy_install 失败:创建进程失败

    关注这篇文章后 如何在 Windows 上安装 pip https stackoverflow com questions 4750806 how to install pip on windows在我使用 Enthought Canopy
  • 仅在配置时才在 Vagrantfile 中运行代码

    我想在运行时在屏幕上显示一些文本vagrant up or vagrant provision etc 当且仅当正在配置 为了vagrant up它仅在第一次运行 或者如果特别强制 provision 如何才能做到这一点 添加 shell
  • Android/Java 创建辅助类来创建图表

    Goal 创建用于图形生成的辅助类 背景 我有 3 个片段 每个片段收集一些传感器数据 加速度计 陀螺仪 旋转 并使用 GraphView 绘制图表 以下是其中一个片段的代码 该代码当前工作正常 public class Gyroscope