尝试使用Android绘图绘制图形时出现NullPointerException

时间:2011-05-07 19:22:30

标签: android drawing nullpointerexception

我想草拟一个跟踪用户体重进度的图表,
我正在写一个方法,我可以在onCreat事件中调用,
 这是我的代码:

 public void drawGraph(){
    Display display = getWindowManager().getDefaultDisplay();   
private int width = display.getWidth();  
private int height = display.getHeight();                                               
    Paint paint = new Paint();
    Canvas canvas =new Canvas();
    paint.setColor(Color.GRAY);
    canvas.drawLine(0, 0, 0, height, paint); // the x-axes represent the date        
    canvas.drawLine(0, height, width, height, paint); // the y-axes represent the weight  

    paint.setColor(Color.RED);
    canvas.drawLine(0, max, width, max, paint); //draw the maximum healthy weight
    paint.setColor(Color.YELLOW);
    canvas.drawLine(0, min, width, min, paint); // draw the minimum healthy weight
    paint.setColor(Color.GREEN);
    canvas.drawLine(0, gW, width, gW, paint); // draw the goal weight
            int xDis = width/weekNumbers;
            int y;
    Path path = new Path();     
    for (int i = 0; i <= Weightvalues; i++){
        Cursor c = db.rawQuery("SELECT CURRENTWEIGHT FROM WEIGHT WHERE DATECREATED > " + startDate, null);
        int weight;
        if (c!=null){
            if (c.moveToFirst()){
                do{
                    weight = c.getInt(0);
                    // I want now to find out for each entry the point represent it on the graph
                    y = Math.round(weight * y / range); //range is the difference between the maximum weight and the minimum weight
                    if (i==1)
                        path.moveTo(0, y);
                    else
                        path.lineTo(0 + i*xDis, height-y);

                }while(c.moveToNext());
            }
        }
    }
    paint.setColor(Color.BLUE);
    canvas.drawPath(path, paint);

}  

这是onCreat事件

protected void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.weight_chart);
      helper = new DataBaseHelper(this);
      drawGraph();
}

当我运行程序时,我遇到了这个错误

    ERROR/AndroidRuntime(738): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{*********.WeightChart}: java.lang.NullPointerException

任何机构都可以为我审查并告诉我哪里出错了

祝你好运

1 个答案:

答案 0 :(得分:2)

你似乎使用Canvas而没有为它指定一个Bitmap来绘图。要在屏幕上显示图像,一种方法是在布局xml中定义ImageView;

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/graph_image" />

伴随对drawGraph方法的以下更改;

...
Bitmap bitmap = BitmapCreateBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas = new Canvas(bitmap);
...
Do your drawing stuff..
...
ImageView iv = (ImageView)findViewById(R.id.graph_image);
iv.setImageBitmap(bitmap);
}
相关问题