我想使用sqlite中的数据显示饼图。我将数据输出到列表中以获得饼图的条目。但是代码似乎有问题,我不知道它有什么问题。下面是代码。
public class chart extends Activity {
SQLiteDatabase SQ;
@Override
protected void onCreate (Bundle savedInstanceState){
…
//add data
addData();
//customize legends
Legend l=mChart.getLegend();
l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
l.setXEntrySpace(7);
l.setYEntrySpace(5);
}
public ArrayList<String> queryXData(){
ArrayList<String> xNewData = new ArrayList<String>();
String query="SELECT "+ TableInfo.APPLIANCE +" FROM "+TableInfo.TABLE_NAME;
Cursor cursor = SQ.rawQuery(query,null);
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
xNewData.add(cursor.getString(0));
}
cursor.close();
return xNewData;
}
public ArrayList<Integer> queryYData(){
ArrayList<Integer> yNewData= new ArrayList<Integer>();
String query="SELECT "+ TableInfo.POWER_USED +" FROM "+TableInfo.TABLE_NAME;
Cursor cursor=SQ.rawQuery(query,null);
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
yNewData.add(cursor.getInt(5));
}
cursor.close();
return yNewData;
}
private void addData() {
ArrayList<Entry> yVals = new ArrayList<Entry>();
for (int i = 0; i < queryYData().size(); i++)
yVals.add(new Entry(queryYData().get(i), i));
ArrayList<String> xVals = new ArrayList<String>();
for (int i = 0; i < queryXData().size(); i++)
xVals.add(queryXData().get(i));
//create pie data set
PieDataSet dataSet=new PieDataSet(yVals,"Appliances");
dataSet.setSliceSpace(3); // space between each arc slice
dataSet.setSelectionShift(5);
//add many colors
ArrayList<Integer> colors=new ArrayList<Integer>();
for(int c: ColorTemplate.VORDIPLOM_COLORS)
colors.add(c);
for(int c: ColorTemplate.JOYFUL_COLORS)
colors.add(c);
for(int c: ColorTemplate.COLORFUL_COLORS)
colors.add(c);
for(int c: ColorTemplate.LIBERTY_COLORS)
colors.add(c);
for(int c: ColorTemplate.PASTEL_COLORS)
colors.add(c);
colors.add(ColorTemplate.getHoloBlue());
dataSet.setColors(colors);
//instantiate pie data object now
PieData data=new PieData(xVals, dataSet);
data.setValueFormatter(new PercentFormatter());
data.setValueTextSize(11f);
data.setValueTextColor(Color.GRAY);
mChart.setData(data);
//undo all highlights
mChart.highlightValues(null);
//update pie chart
mChart.invalidate();
//demo start
}
}
Aboce是我尝试的代码,但有错误,主要是
chart.queryYData(chart.java:100)
Cursor cursor=SQ.rawQuery(query,null);
chart.addData(chart.java:111)for (int i = 0; i < queryYData().size(); i++)
chart.onCreate(chart.java:76)addData();
这些错误导致应用程序“不幸,应用程序停止了”。有人可以帮我弄这个吗?谢谢。
答案 0 :(得分:0)
例如,您需要添加一行来标识mChart。其他代码看起来很好。
mChart=(PieChart)findViewByID(R.id.pieChart);