这是我在 android 中的条形图代码 我得到以下错误

发布于 2024-11-08 00:36:37 字数 9074 浏览 4 评论 0原文

这是我的主要活动类

    package android.graph.graphview;

    import android.app.Activity;
    import android.graphics.Canvas;
    import android.os.Bundle;

    public class GraphView extends Activity {
/** Called when the activity is first created. */
GraphViewDemo mGraphViewDemo;
Canvas mCanvas = new Canvas();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mGraphViewDemo = (GraphViewDemo) findViewById(R.id.graphview);
    float[] values = new float[] { 1.0f, 6.0f, 7.0f, 8.0f, 9.0f, 3.0f,
            2.0f, 10.0f, 6.0f, 7.0f, 8.0f, 9.0f, 1.0f };
    String[] verlabels = new String[] { "great", "ok", "bad" };
    String[] horlabels = new String[] { "today", "tomorrow", "next week",
            "next month", "Next Year" };
    mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
            horlabels, verlabels, GraphViewDemo.BAR);
    mGraphViewDemo.draw(mCanvas);

}

}

这是我在 GraphViewDemo.java 中定义绘制条形图视图的类

    package android.graph.graphview;

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Paint.Align;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.View;

    public class GraphViewDemo extends View {

public static boolean BAR = true;
public static boolean LINE = false;

private Paint paint;
private float[] values;
private String[] horlabels;
private String[] verlabels;
private String title;
private boolean type;

public GraphViewDemo(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public GraphViewDemo(Context context, float[] values, String title,
        String[] horlabels, String[] verlabels, boolean type) {
    super(context);
    if (values == null)
        values = new float[0];
    else
        this.values = values;
    if (title == null)
        title = "";
    else
        this.title = title;
    if (horlabels == null)
        this.horlabels = new String[0];
    else
        this.horlabels = horlabels;
    if (verlabels == null)
        this.verlabels = new String[0];
    else
        this.verlabels = verlabels;
    this.type = type;
    paint = new Paint();
}

@Override
protected void onDraw(Canvas canvas) {
    float border = 20;
    float horstart = border * 2;
    float height = getHeight();
    float width = getWidth() - 1;
    float max = getMax();    << also here i get NPE error in my Logcat >>
    float min = getMin();
    float diff = max - min;
    float graphheight = height - (2 * border);
    float graphwidth = width - (2 * border);


    paint.setTextAlign(Align.LEFT);
    int vers = verlabels.length - 1;
    for (int i = 0; i < verlabels.length; i++) {
        // paint.setColor(Color.RED);
        float y = ((graphheight / vers) * i) + border;
        // canvas.drawLine(horstart, y, width, y, paint);
        paint.setColor(Color.WHITE);
        canvas.drawText(verlabels[i], 0, y, paint);
    }
    int hors = horlabels.length - 1;
    for (int i = 0; i < horlabels.length; i++) {
        // paint.setColor(Color.BLUE);
        float x = ((graphwidth / hors) * i) + horstart;
        // canvas.drawLine(x, height - 50, x, border, paint);
        paint.setTextAlign(Align.CENTER);
        if (i == horlabels.length - 1)
            paint.setTextAlign(Align.RIGHT);
        if (i == 0)
            paint.setTextAlign(Align.LEFT);
        paint.setColor(Color.WHITE);
        canvas.drawText(horlabels[i], x, height - 4, paint);
    }

    paint.setTextAlign(Align.CENTER);
    canvas.drawText(title, (graphwidth / 2) + horstart, border - 4, paint);

    if (max != min) {
        paint.setColor(Color.LTGRAY);
        if (type == BAR) {
            int minus = 10;
            float datalength = values.length;
            float colwidth = (width - (2 * border)) / datalength;
            for (int i = 0; i < values.length; i++) {
                float val = values[i] - min;
                float rat = val / diff;
                float h = graphheight * rat;
                canvas.drawRect((i * colwidth) + horstart,
                        ((border - h) + graphheight) + 100,
                        (((i * colwidth) + horstart) + (colwidth - 1))
                                - minus, ((height - (border - 1) - 50)),
                        paint);
                // (border - h)+ graphheight

            }

        }
    }
}

private float getMax() {
    float largest = Integer.MIN_VALUE;
    for (int i = 0; i < values.length; i++)   <<in this line i get NPE
        // if (values[i] > largest)
        // largest = values[i];
        largest = 10;
    Log.v("log_tag", "All Data max of getmax " + largest);
    return largest;
}

private float getMin() {
    float smallest = Integer.MAX_VALUE;
    for (int i = 0; i < values.length; i++)
        // if (values[i] < smallest)
        smallest = -5;
    Log.v("log_tag", "All Data min get min  " + smallest);
    return smallest;
}

}

现在这是我的 main.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
<android.graph.graphview.GraphViewDemo
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:id="@+id/graphview" />
</LinearLayout>

这是我的错误,所以请解决这个问题。

    05-16 16:43:17.392: ERROR/AndroidRuntime(822): FATAL EXCEPTION: main
    05-16 16:43:17.392: ERROR/AndroidRuntime(822): java.lang.NullPointerException
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at            android.graph.graphview.GraphViewDemo.getMax(GraphViewDemo.java:159)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.graph.graphview.GraphViewDemo.onDraw(GraphViewDemo.java:57)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6740)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1640)      
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6743)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.widget.FrameLayout.draw(FrameLayout.java:352)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1640 )
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6743)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.widget.FrameLayout.draw(FrameLayout.java:352)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1842)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.draw(ViewRoot.java:1407)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1163)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.os.Handler.dispatchMessage(Handler.java:99)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.os.Looper.loop(Looper.java:123)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at java.lang.reflect.Method.invoke(Method.java:521)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at dalvik.system.NativeStart.main(Native Method)

我想要这个解决方案在 xml 文件中,而不是任何内容视图中,所以请检查它。

Here is the my main activity class

    package android.graph.graphview;

    import android.app.Activity;
    import android.graphics.Canvas;
    import android.os.Bundle;

    public class GraphView extends Activity {
/** Called when the activity is first created. */
GraphViewDemo mGraphViewDemo;
Canvas mCanvas = new Canvas();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mGraphViewDemo = (GraphViewDemo) findViewById(R.id.graphview);
    float[] values = new float[] { 1.0f, 6.0f, 7.0f, 8.0f, 9.0f, 3.0f,
            2.0f, 10.0f, 6.0f, 7.0f, 8.0f, 9.0f, 1.0f };
    String[] verlabels = new String[] { "great", "ok", "bad" };
    String[] horlabels = new String[] { "today", "tomorrow", "next week",
            "next month", "Next Year" };
    mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
            horlabels, verlabels, GraphViewDemo.BAR);
    mGraphViewDemo.draw(mCanvas);

}

}

Here is the my class where i define view for draw bar chart in GraphViewDemo.java

    package android.graph.graphview;

    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Paint.Align;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.View;

    public class GraphViewDemo extends View {

public static boolean BAR = true;
public static boolean LINE = false;

private Paint paint;
private float[] values;
private String[] horlabels;
private String[] verlabels;
private String title;
private boolean type;

public GraphViewDemo(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public GraphViewDemo(Context context, float[] values, String title,
        String[] horlabels, String[] verlabels, boolean type) {
    super(context);
    if (values == null)
        values = new float[0];
    else
        this.values = values;
    if (title == null)
        title = "";
    else
        this.title = title;
    if (horlabels == null)
        this.horlabels = new String[0];
    else
        this.horlabels = horlabels;
    if (verlabels == null)
        this.verlabels = new String[0];
    else
        this.verlabels = verlabels;
    this.type = type;
    paint = new Paint();
}

@Override
protected void onDraw(Canvas canvas) {
    float border = 20;
    float horstart = border * 2;
    float height = getHeight();
    float width = getWidth() - 1;
    float max = getMax();    << also here i get NPE error in my Logcat >>
    float min = getMin();
    float diff = max - min;
    float graphheight = height - (2 * border);
    float graphwidth = width - (2 * border);


    paint.setTextAlign(Align.LEFT);
    int vers = verlabels.length - 1;
    for (int i = 0; i < verlabels.length; i++) {
        // paint.setColor(Color.RED);
        float y = ((graphheight / vers) * i) + border;
        // canvas.drawLine(horstart, y, width, y, paint);
        paint.setColor(Color.WHITE);
        canvas.drawText(verlabels[i], 0, y, paint);
    }
    int hors = horlabels.length - 1;
    for (int i = 0; i < horlabels.length; i++) {
        // paint.setColor(Color.BLUE);
        float x = ((graphwidth / hors) * i) + horstart;
        // canvas.drawLine(x, height - 50, x, border, paint);
        paint.setTextAlign(Align.CENTER);
        if (i == horlabels.length - 1)
            paint.setTextAlign(Align.RIGHT);
        if (i == 0)
            paint.setTextAlign(Align.LEFT);
        paint.setColor(Color.WHITE);
        canvas.drawText(horlabels[i], x, height - 4, paint);
    }

    paint.setTextAlign(Align.CENTER);
    canvas.drawText(title, (graphwidth / 2) + horstart, border - 4, paint);

    if (max != min) {
        paint.setColor(Color.LTGRAY);
        if (type == BAR) {
            int minus = 10;
            float datalength = values.length;
            float colwidth = (width - (2 * border)) / datalength;
            for (int i = 0; i < values.length; i++) {
                float val = values[i] - min;
                float rat = val / diff;
                float h = graphheight * rat;
                canvas.drawRect((i * colwidth) + horstart,
                        ((border - h) + graphheight) + 100,
                        (((i * colwidth) + horstart) + (colwidth - 1))
                                - minus, ((height - (border - 1) - 50)),
                        paint);
                // (border - h)+ graphheight

            }

        }
    }
}

private float getMax() {
    float largest = Integer.MIN_VALUE;
    for (int i = 0; i < values.length; i++)   <<in this line i get NPE
        // if (values[i] > largest)
        // largest = values[i];
        largest = 10;
    Log.v("log_tag", "All Data max of getmax " + largest);
    return largest;
}

private float getMin() {
    float smallest = Integer.MAX_VALUE;
    for (int i = 0; i < values.length; i++)
        // if (values[i] < smallest)
        smallest = -5;
    Log.v("log_tag", "All Data min get min  " + smallest);
    return smallest;
}

}

And Now here is my main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="@string/hello" />
<android.graph.graphview.GraphViewDemo
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:id="@+id/graphview" />
</LinearLayout>

Here is my error so please solved this.

    05-16 16:43:17.392: ERROR/AndroidRuntime(822): FATAL EXCEPTION: main
    05-16 16:43:17.392: ERROR/AndroidRuntime(822): java.lang.NullPointerException
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at            android.graph.graphview.GraphViewDemo.getMax(GraphViewDemo.java:159)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.graph.graphview.GraphViewDemo.onDraw(GraphViewDemo.java:57)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6740)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1640)      
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6743)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.widget.FrameLayout.draw(FrameLayout.java:352)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1640 )
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.View.draw(View.java:6743)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.widget.FrameLayout.draw(FrameLayout.java:352)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1842)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.draw(ViewRoot.java:1407)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1163)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.os.Handler.dispatchMessage(Handler.java:99)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.os.Looper.loop(Looper.java:123)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at java.lang.reflect.Method.invokeNative(Native Method)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at java.lang.reflect.Method.invoke(Method.java:521)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    05-16 16:43:17.392: ERROR/AndroidRuntime(822):     at dalvik.system.NativeStart.main(Native Method)

I want this solution in xml file not any content view so please check it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゞ记忆︶ㄣ 2024-11-15 00:36:37
mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
        horlabels, verlabels, GraphViewDemo.BAR);
mGraphViewDemo.draw(mCanvas);

我认为,您的意图是覆盖已经膨胀的视图对象。这不会执行此操作,因此您仍然拥有未正确初始化的视图,因此会出现 NullPointerException。从 xml 中删除视图,然后将创建的(在 onCreate() 中)视图添加到布局中。

setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);// don't forget to mention id in xml
float[] values = new float[] { 1.0f, 6.0f, 7.0f, 8.0f, 9.0f, 3.0f,
        2.0f, 10.0f, 6.0f, 7.0f, 8.0f, 9.0f, 1.0f };
String[] verlabels = new String[] { "great", "ok", "bad" };
String[] horlabels = new String[] { "today", "tomorrow", "next week",
        "next month", "Next Year" };
mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
        horlabels, verlabels, GraphViewDemo.BAR);
layout.add(mGraphViewDemo);

另外,您不应该实例化 Canvas 对象,也不应该手动尝试绘制视图。所有自定义绘图必须放置在视图的 onDraw() 方法中。

mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
        horlabels, verlabels, GraphViewDemo.BAR);
mGraphViewDemo.draw(mCanvas);

I think, your intention was to overwrite the view object which is already inflated. This doesn't do this, so you still have the view, which is not properly initialized and thus getting NullPointerException. Remove the view from xml and simply add the created(in onCreate()) view to the layout.

setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);// don't forget to mention id in xml
float[] values = new float[] { 1.0f, 6.0f, 7.0f, 8.0f, 9.0f, 3.0f,
        2.0f, 10.0f, 6.0f, 7.0f, 8.0f, 9.0f, 1.0f };
String[] verlabels = new String[] { "great", "ok", "bad" };
String[] horlabels = new String[] { "today", "tomorrow", "next week",
        "next month", "Next Year" };
mGraphViewDemo = new GraphViewDemo(this, values, "GraphViewDemo",
        horlabels, verlabels, GraphViewDemo.BAR);
layout.add(mGraphViewDemo);

Also, you should NOT instantiate a Canvas object, and you should NOT manually try to draw your view. All custom drawing must be placed in onDraw() method of the view.

好多鱼好多余 2024-11-15 00:36:37

getMax 中 NPE 的唯一原因是 values 等于 null

这是在构造函数中的以下代码中启动的:

public GraphViewDemo(Context context, float[] values, String title,
    String[] horlabels, String[] verlabels, boolean type) {
  super(context);

  if (values == null)
    values = new float[0];
  else
    this.values = values;

看看如果您创建一个实例并为 values 传递 null 会发生什么? 本地变量values使用零大小数组进行初始化,而类属性values仍然是

这将解决问题:(

  if (values == null)
    this.values = new float[0];  // <-- change in this line
  else
    this.values = values;

顺便说一句 - 一个非常常见的错误...)


View 的 Javadoc 指出:

View(Context context, AttributeSet attrs)
    Constructor that is called when inflating a view from XML.

很有可能,您的实际 View 子类实例具有是使用另一个已定义的构造函数创建的,并且不会初始化字段。只需向其他构造函数主体添加一条日志语句即可检查是否属于这种情况。

The only reason for a NPE in getMax is values being equal to null.

And this is initiated in the constructor at this code:

public GraphViewDemo(Context context, float[] values, String title,
    String[] horlabels, String[] verlabels, boolean type) {
  super(context);

  if (values == null)
    values = new float[0];
  else
    this.values = values;

See what happens if you create an instance and pass null for values? The local variable values is initialized with a zero-size array while the class attribute values is still null.

This will fix the issue:

  if (values == null)
    this.values = new float[0];  // <-- change in this line
  else
    this.values = values;

(btw - a very common bug...)


The Javadoc for View states:

View(Context context, AttributeSet attrs)
    Constructor that is called when inflating a view from XML.

There is a good chance, that your actual View subclass instance has been created with the other constructor which is defined and does not init the fields. Simply add a log statement to the other constructors body to check if this is the case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文