2017-03-09 94 views
0

我想創建一個使用BARCHART但MPAndroidChart我收到以下錯誤java.lang.ClassCastException: com.github.mikephil.charting.data.Entry cannot be cast to com.github.mikephil.charting.data.BarEntryMPAndroidChart項不能被轉換爲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); 

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

我看不出我只使用Entry,而不是BarEntry任何地方。我的xml也說BarChart不是LineChart。

+0

感謝您接受@生命! –

回答

0

使用MPAndroidChart 3.0.1

我很抱歉地說,這看起來像一個未完全執行的BarEntry。如果您查看源代碼,你可以看到如下:

  1. BarEntry延伸Entry
  2. Entry實現Parcelable
  3. BarEntry沒有自己的Parcelable<Creator>

所以當你連載到包裹,然後反序列化,您將得到一個List<Entry>而不是List<BarEntry> :-)

現在除了解決這個問題之外,沒有什麼可以做的。

您可以藉此機會重構以實現更好的圖層分離。 BarEntry是視圖圖層或視圖模型圖層的成員。而不是傳遞BarEntry,你應該有一個清晰的模型層,它僅僅是一個數據對象。您可以輕鬆地將此模型層的列表或數組傳遞給Intent,並且消費者可以根據需要將其轉換爲BarEntry

或者,創建一個數據源的抽象。類似於TemperatureRepository類。然後,使用此數據的活動和片段可以從存儲庫中獲取數據,而不是從Intent中獲取數據。

相關問題