我想從存儲在數據庫中的數據使用MPAndroidChart創建一個餅圖。 數據庫的大小不固定,因此可能有2到7個數據。我無法解決這個MPAndroidChart空對象引用錯誤
這是我如何從數據庫中獲取數據。
myDb = new DatabaseHelper(this);
Cursor pie = myDb.showKharcha();
String[] xData = new String[pie.getCount()];
float[] yData = new float[pie.getCount()];
int i = 0;
float total = 0;
while (pie.moveToNext()){
String kname = pie.getString(1);
Float kh= pie.getFloat(2);
float kharcha = kh.floatValue();
total = total + kharcha ;
xData[i]=kname;
yData[i]=kharcha;
i++;
}
這是使用餅圖的數據的一部分。
ArrayList<PieEntry> yEntry= new ArrayList<>();
ArrayList<String> xEntry = new ArrayList<>();
for(i =0;i < yData.length;i++){
yData[i] = yData[i]*100/total;
yEntry.add(new PieEntry(yData[i],i));
}
for(i =0;i < xData.length;i++){
xEntry.add(xData[i]);
}
我得到的錯誤是空指針異常錯誤,這是精確
Attempt to invoke virtual method 'void com.github.mikephil.charting.charts.PieChart.setRotationEnabled(boolean)' on a null object reference
含有setRotationEnabled(布爾值)的部分是如下這是調用addDataSet方法之前,一切我已經提供了。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.piechart);
Log.d(TAG, "onCreate: starting to create chart");
pieChart.setRotationEnabled(true);
pieChart.setHoleRadius(25f);
pieChart.setTransparentCircleAlpha(0);
pieChart.setCenterText("Kharcha");
pieChart.setCenterTextSize(10);
addDataSet();}
我想我不能夠通過浮動數據在餅圖中使用。 任何幫助,將不勝感激。
添加您的整個班級,因爲您在'setRotationEnabled()'行有問題 –
@OussemaAroua我已經添加了您所要求的內容。如果我刪除了setRotationEnabled(true),那麼跟在它後面的行就會出現同樣的錯誤,等等。 –