问题
I want to create a BarChart using MPAndroidChart but I get the following error java.lang.ClassCastException: com.github.mikephil.charting.data.Entry cannot be cast to com.github.mikephil.charting.data.BarEntry
I first get the data from a different activity and use that.
First activity:
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);
In DeviceDataReport:
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);
}
I don't see any place where I am only using Entry
instead of BarEntry
. My xml also says BarChart not LineChart.
回答1:
Using MPAndroidChart 3.0.1
I'm sorry to say this looks like an incomplete implementation of BarEntry
. If you inspect the source, you can see the following:
BarEntry
extendsEntry
Entry
implementsParcelable
BarEntry
doesn't have its ownParcelable<Creator>
So when you serialise into a parcel, and then deserialise, you'll get a List<Entry>
instead of List<BarEntry>
:-)
For now there is nothing you can do apart from work around this.
You can take the opportunity to refactor to achieve a better separation of layers. BarEntry
is a member of the view layer or the view model layer. Instead of passing around BarEntry
, you should probably have a clear model layer which is a mere data object. You can pass lists or arrays of this model layer around in an Intent easily and the consumers can convert to BarEntry
as necessary.
Alternatively, create an abstraction of a data source. Something like a TemperatureRepository
class. Then Activitys and Fragments that consume this data can get the data from the repository rather than from an Intent.
来源:https://stackoverflow.com/questions/42685927/mpandroidchart-entry-cannot-be-cast-to-barentry