【问题标题】:MPAndroidChart Entry cannot be cast to BarEntryMPAndroidChart 条目无法转换为 BarEntry
【发布时间】:2017-03-09 03:06:50
【问题描述】:

我想使用 MPAndroidChart 创建条形图,但收到以下错误 java.lang.ClassCastException: com.github.mikephil.charting.data.Entry cannot be cast to com.github.mikephil.charting.data.BarEntry

我首先从不同的活动中获取数据并使用它。

第一个活动:

ArrayList<BarEntry> temperature = new ArrayList<>();
for (int i = 0; i < temp.length(); i++) {
    float temp_data = Float.parseFloat(temp.getJSONObject(i).getString("value"));
    float humid_data = Float.parseFloat(humid.getJSONObject(i).getString("value"));
    float time_data = Float.parseFloat(time.getJSONObject(i).getString("time"));

    temperature.add(new BarEntry(time_data, temp_data));
                                humidity.add(new BarEntry(time_data, humid_data));
    }
Intent intent = new Intent(itemView.getContext(), DeviceDataReport.class);
intent.putExtra("temperatureData", temperature);
//put other extras

context.startActivity(intent);

在设备数据报告中:

ArrayList<BarEntry> temperature = new ArrayList<>();
if (extras != null) {
        temperature = extras.getParcelableArrayList("temperatureData");
        //get other data
    }


temperatureChart = (BarChart) findViewById(R.id.chart_temp);
BarDataSet set1;
    if (temperatureChart.getData() != null &&
            temperatureChart.getData().getDataSetCount() > 0) {
        set1 = (BarDataSet) temperatureChart.getData().getDataSetByIndex(0);
        set1.setValues(temperature);
        temperatureChart.getData().notifyDataChanged();
        temperatureChart.notifyDataSetChanged();
    } else {
        set1 = new BarDataSet(temperature, "The year 2017"); //this is where error occurs

        ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(dataSets);

        temperatureChart.setData(data);
    }

我没有看到我只使用Entry 而不是BarEntry 的任何地方。我的 xml 还说 BarChart 而不是 LineChart。

【问题讨论】:

  • 感谢接受@Tirth!

标签: java android casting mpandroidchart


【解决方案1】:

使用 MPAndroidChart 3.0.1

很抱歉,这看起来像是 BarEntry 的不完整实现。如果您检查源代码,您可以看到以下内容:

  1. BarEntry 扩展 Entry
  2. Entry 实现 Parcelable
  3. BarEntry 没有自己的 Parcelable&lt;Creator&gt;

因此,当您将序列化为包裹,然后反序列化时,您将得到 List&lt;Entry&gt; 而不是 List&lt;BarEntry&gt; :-)

目前,除了解决这个问题,您无能为力。

您可以借此机会进行重构以实现更好的层分离。 BarEntry 是视图层或视图模型层的成员。而不是传递BarEntry,您可能应该有一个清晰的模型层,它只是一个数据对象。您可以轻松地在 Intent 中传递此模型层的列表或数组,消费者可以根据需要转换为BarEntry

或者,创建数据源的抽象。类似于TemperatureRepository 类。然后使用这些数据的 Activity 和 Fragment 可以从存储库而不是 Intent 中获取数据。

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多