在Android中使用Achartengine的饼图

时间:2015-03-23 04:18:33

标签: android graph achartengine

当我可以在不同的情况下调用此方法时,将绘制图形,但问题是它与前一个重叠。我已经尝试了很多来清除上一张图,但却无法做到。请任何人帮我实现同样的目标。

由于我还附上了截图以及整个代码,在日期部分的点击按钮上,我想绘制该特定日期的图表。 但是您可以在附加图像中看到数据仅在前一个数据上重叠。 thnks。

 //imports here
  public class NutrientDailyTrackerActivity extends Fragment {

  private static int[] COLORS = new int[] {        Color.parseColor("#4CC1D2"),Color.parseColor("#FE2E2E"), Color.parseColor("#298A08") };*  



private static String[] NAME_LIST = new String[] { "Fat", "Carbs", "Protein"};  

private CategorySeries mSeries = new CategorySeries("");  

private DefaultRenderer mRenderer = new DefaultRenderer();  

private GraphicalView mChartView;  
private String formattedDate;
private TextView currentDate;
private ImageView prevMonth;
private ImageView nextMonth;
private TextView dailyfat;
private TextView dailycarbs;
private String checkingdate;
Calendar c;
Calendar d;
SimpleDateFormat df;
Date date1;
Date date2;
DatabaseHandler db ;
private String uniquecaloriestring ;
private String uniquefat;
private String uniquecarbohydrate ;
private String uniqueprotein;
LinearLayout layout=null;

private static final String DATABASE_NAME = "ndietguru.db";

private double ddcalorie ;
private double ddcalorieconsumed ;
private double ddcalorieburned ;
private double ddfatgoal ;
private double ddproteingoal ;
private double ddcarbohydrategoal;

private double dFat;
private double dCarbs;
private double dProteins;



private double dunical ;
private double dunifat ;
private double dunicarbs ;
private double duniprotein;

private int dbtotalfat;
private int dbtotalcarbs;
private int dbtotalproteins;


private int dbcalorie;
private int dbcalorieburned;
View rootView=null;
private double calorie;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.activity_nutrient_details, container, false);  


    currentDate = (TextView)rootView.findViewById(R.id.currentMonth);
    prevMonth = (ImageView)rootView.findViewById(R.id.prevMonth);
    nextMonth = (ImageView)rootView.findViewById(R.id.nextMonth);

    db = new DatabaseHandler(getActivity());
    HashMap<String, String> user = new HashMap<String, String>();
    user = db.getUserCalDetails();

    uniquefat = (String) user.get("fat");
    uniquecarbohydrate = (String) user.get("carbohydrate");
    uniqueprotein = (String) user.get("protein");


    if(formattedDate == null){
        c = Calendar.getInstance();
        df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
        formattedDate = df.format(c.getTime());
        try {
            date1 = df.parse(formattedDate);
            c.setTime(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    else{
        System.out.println("date in fragment" + formattedDate);
        c = Calendar.getInstance();
        df = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
        System.out.println("inside else");
        try {
            date1 = df.parse(formattedDate);
            c.setTime(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    //calendar for checking date
    d = Calendar.getInstance();
    checkingdate = df.format(d.getTime());
    try {
        date2 = df.parse(checkingdate);
        d.setTime(date2);
    } catch (ParseException e) {

        e.printStackTrace();
    }
    if(date1.equals(date2))
    {
        nextMonth.setVisibility(View.GONE);
    }

    else
    {
        nextMonth.setVisibility(View.VISIBLE);
    }
    selectdata();

    dbtotalfat = Math.round(dbtotalfat);

    dbtotalcarbs = Math.round(dbtotalcarbs);

    dbtotalproteins = Math.round(dbtotalproteins);

    int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };

    currentDate.setText(formattedDate);
    drawGraph(VALUES);


    prevMonth.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            c.add(Calendar.DATE, -1);
            formattedDate = df.format(c.getTime());
            currentDate.setText(formattedDate);
            d = Calendar.getInstance();
            checkingdate = df.format(d.getTime());
            if(formattedDate.equals(checkingdate))
            {
                nextMonth.setVisibility(View.GONE);
            }
            else
            {
                nextMonth.setVisibility(View.VISIBLE);
            }
            selectprevdata();


            dbtotalfat = Math.round(dbtotalfat);

            dbtotalcarbs = Math.round(dbtotalcarbs);

            dbtotalproteins = Math.round(dbtotalproteins);
            System.out.println("on prev fat"+dbtotalfat);
            System.out.println("on prev carbs"+dbtotalcarbs);
            System.out.println("on prev Pro"+dbtotalproteins);


            int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };
            currentDate.setText(formattedDate);
            drawGraph(VALUES);

            System.out.println("From outside Block"); 
            System.out.println("This is formated date"+formattedDate);

        }
    });

    //Next Button For Date
    nextMonth.setOnClickListener(new OnClickListener() {
        @Override public void onClick(View v){

            c.add(Calendar.DATE, 1);
            formattedDate = df.format(c.getTime());
            currentDate.setText(formattedDate);
            final Calendar d = Calendar.getInstance();
            checkingdate = df.format(d.getTime());

            if(formattedDate.equals(checkingdate))
            {
                nextMonth.setVisibility(View.GONE);
            }
            else
            {
                nextMonth.setVisibility(View.VISIBLE);
            }

            selectnextdata();

            dbtotalfat = Math.round(dbtotalfat);

            dbtotalcarbs = Math.round(dbtotalcarbs);

            dbtotalproteins = Math.round(dbtotalproteins);


            int[] VALUES = new int[] {dbtotalfat, dbtotalcarbs, dbtotalproteins };

            currentDate.setText(formattedDate);

            drawGraph(VALUES);

        }
    });


    return rootView;  

}  



private void selectdata() {

    DatabaseHandler helper = new DatabaseHandler(getActivity());
    SQLiteDatabase db = helper.getReadableDatabase();
    String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
    String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
    String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
    Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
    Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
    Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);


    if (!calorieConsumedQueryCursor.isAfterLast()) {
        calorieConsumedQueryCursor.moveToFirst();

        while (!calorieConsumedQueryCursor.isAfterLast()) {
            dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));

            dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
            dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
            dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
            calorieConsumedQueryCursor.moveToNext();
        }
    }
    if (!calorieBurnedQueryCursor.isAfterLast()) {
        calorieBurnedQueryCursor.moveToFirst();

        while (!calorieBurnedQueryCursor.isAfterLast()) {
            dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
            Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
            calorieBurnedQueryCursor.moveToNext();
        }
    }
    if (!calorieDetailsQueryCursor.isAfterLast()) {
        calorieDetailsQueryCursor.moveToFirst();

        while (!calorieDetailsQueryCursor.isAfterLast()) {
            calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
            ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
            ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
            dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
            dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
            dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));

            Log.e("Daily info"," ddcalorie: " + calorie);
            Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
            Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
            Log.e("Daily info"," ddfatgoal: " + dFat);
            Log.e("Daily info"," ddproteingoal: " + dProteins);
            Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);


            calorieDetailsQueryCursor.moveToNext();
        }
    }
    calorieConsumedQueryCursor.close();
    calorieBurnedQueryCursor.close();
    calorieDetailsQueryCursor.close();
    db.close();
}
private void selectprevdata() {

    DatabaseHandler helper = new DatabaseHandler(getActivity());
    SQLiteDatabase db = helper.getReadableDatabase();
    String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
    String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
    String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
    Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
    Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
    Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);


    if (!calorieConsumedQueryCursor.isAfterLast()) {
        calorieConsumedQueryCursor.moveToFirst();

        while (!calorieConsumedQueryCursor.isAfterLast()) {
            dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));

            dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
            dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
            dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
            calorieConsumedQueryCursor.moveToNext();
        }
    }
    if (!calorieBurnedQueryCursor.isAfterLast()) {
        calorieBurnedQueryCursor.moveToFirst();

        while (!calorieBurnedQueryCursor.isAfterLast()) {
            dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
            Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
            calorieBurnedQueryCursor.moveToNext();
        }
    }

    if (!calorieDetailsQueryCursor.isAfterLast()) {
        calorieDetailsQueryCursor.moveToFirst();

        while (!calorieDetailsQueryCursor.isAfterLast()) {
            calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
            ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
            ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
            dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
            dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
            dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));

            Log.e("Daily info"," ddcalorie: " + calorie);
            Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
            Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
            Log.e("Daily info"," ddfatgoal: " + dFat);
            Log.e("Daily info"," ddproteingoal: " + dProteins);
            Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);


            calorieDetailsQueryCursor.moveToNext();
        }
    }
    calorieConsumedQueryCursor.close();
    calorieBurnedQueryCursor.close();
    calorieDetailsQueryCursor.close();
    db.close();
}
private void selectnextdata() {

    DatabaseHandler helper = new DatabaseHandler(getActivity());
    SQLiteDatabase db = helper.getReadableDatabase();
    String calorieConsumedQuery = "SELECT SUM(calorie) AS dbcalorie,SUM(fat) AS dbtotalfat,SUM(carbohydrate) AS dbtotalcarbs,SUM(protein)AS Totalprotein FROM Meal WHERE createddate = ('"+formattedDate+"')";
    String caloriBurnedQuery = "SELECT SUM(calorieburned) AS dbcalorieburned FROM ExerciseData WHERE createddate = ('"+formattedDate+"')";
    String calorieDetailsQuery = "SELECT caloriegoal, calorieconsumed,calorieburned, fatgoal, proteingoal,carbohydrategoal FROM dailyDetails WHERE createddate = (SELECT MAX(createddate) FROM dailyDetails WHERE createddate <= ('"+formattedDate+"'))";
    Cursor calorieConsumedQueryCursor = db.rawQuery(calorieConsumedQuery,null);
    Cursor calorieBurnedQueryCursor = db.rawQuery(caloriBurnedQuery,null);
    Cursor calorieDetailsQueryCursor = db.rawQuery(calorieDetailsQuery,null);


    if (!calorieConsumedQueryCursor.isAfterLast()) {
        calorieConsumedQueryCursor.moveToFirst();

        while (!calorieConsumedQueryCursor.isAfterLast()) {
            dbcalorie= (int) Math.round(calorieConsumedQueryCursor.getDouble(0));

            dbtotalfat = (int) Math.round(calorieConsumedQueryCursor.getDouble(1));
            dbtotalcarbs = (int) Math.round(calorieConsumedQueryCursor.getDouble(2));
            dbtotalproteins = (int) Math.round(calorieConsumedQueryCursor.getDouble(3));
            calorieConsumedQueryCursor.moveToNext();
        }
    }
    if (!calorieBurnedQueryCursor.isAfterLast()) {
        calorieBurnedQueryCursor.moveToFirst();

        while (!calorieBurnedQueryCursor.isAfterLast()) {
            dbcalorieburned = (int) Math.round(calorieBurnedQueryCursor.getDouble(0));
            Log.e("calorie info"," dbcalorieburned: " + dbcalorieburned);
            calorieBurnedQueryCursor.moveToNext();
        }
    }

    if (!calorieDetailsQueryCursor.isAfterLast()) {
        calorieDetailsQueryCursor.moveToFirst();

        while (!calorieDetailsQueryCursor.isAfterLast()) {
            calorie = (int) Math.round(calorieDetailsQueryCursor.getDouble(0));
            ddcalorieconsumed = (int) Math.round(calorieDetailsQueryCursor.getDouble(1));
            ddcalorieburned = (int) Math.round(calorieDetailsQueryCursor.getDouble(2));
            dFat = (int) Math.round(calorieDetailsQueryCursor.getDouble(3));
            dProteins = (int) Math.round(calorieDetailsQueryCursor.getDouble(4));
            dCarbs = (int) Math.round(calorieDetailsQueryCursor.getDouble(5));

            Log.e("Daily info"," ddcalorie: " + calorie);
            Log.e("Daily info"," ddcalorieconsumed: " + ddcalorieconsumed);
            Log.e("Daily info"," ddcalorieburned: " + ddcalorieburned);
            Log.e("Daily info"," ddfatgoal: " + dFat);
            Log.e("Daily info"," ddproteingoal: " + dProteins);
            Log.e("Daily info"," ddcarbohydrategoal: " + dCarbs);


            calorieDetailsQueryCursor.moveToNext();
        }
    }
    calorieConsumedQueryCursor.close();
    calorieBurnedQueryCursor.close();
    calorieDetailsQueryCursor.close();
    db.close();
}

void drawGraph(int VALUES[]){


    mRenderer.setApplyBackgroundColor(true);  
    mRenderer.setBackgroundColor(Color.WHITE);  
    mRenderer.setChartTitleTextSize(20);  
    mRenderer.setLabelsTextSize(15);  
    mRenderer.setLegendTextSize(20);  
    mRenderer.setMargins(new int[] { 20, 30, 15, 0 });  
    mRenderer.setStartAngle(90); 
    mRenderer.setPanEnabled(false); 
    mRenderer.setLabelsColor(Color.BLACK);
    mRenderer.setLabelsTextSize(26);


    for (int i = 0; i < VALUES.length; i++) {  
        mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);  
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();  
        renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);  
        mRenderer.addSeriesRenderer(renderer);  
    }  

    if (mChartView != null) {  
        mChartView.repaint();  
    }  


    else if (mChartView == null) {  
        LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.chart); 

        layout.setBackgroundColor(Color.WHITE);
        mChartView = ChartFactory.getPieChartView(getActivity(), mSeries, mRenderer); 
        mChartView.setBackgroundColor(Color.DKGRAY);
        mRenderer.setClickEnabled(true);  
        mRenderer.setSelectableBuffer(10); 


        mChartView.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();  

                if (seriesSelection == null) {  
                    Toast.makeText(getActivity(),"YOu have Clicked",Toast.LENGTH_SHORT).show();  
                } else {  
                    Toast.makeText(getActivity(),"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();  
                }  
            }  
        });  

        mChartView.setOnLongClickListener(new View.OnLongClickListener() {  
            @Override  
            public boolean onLongClick(View v) {  
                SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();  
                if (seriesSelection == null) {  
                    Toast.makeText(getActivity(),"No chart element was long pressed", Toast.LENGTH_SHORT).show();;  
                    return false;   
                } else {  
                    Toast.makeText(getActivity(),"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT).show();  
                    return true;         
                }  
            }  
        });  
        layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));  
    }  
    else {  
        mChartView.repaint();  
    }  
}  

}

enter image description here

1 个答案:

答案 0 :(得分:2)

drawGraph api

中添加这些行
DefaultRenderer mRenderer = new DefaultRenderer(); //move the line 
mSeries.clear()