2012-02-10 81 views
0

朋友..我試圖繪製一些圖。我的應用程序對第​​一次嘗試運行良好,但是當我試圖重複繪製圖形進行2,3次嘗試時,它顯示空指針異常......解決方案是什麼?這裏是我的代碼:在圖生成過程中發生空指針異常

public class ECG extends Activity { 
    /** Called when the activity is first created. */ 
    Context cnt; 
    Callback c; 
    Camera mCamera; 
    boolean mFinished; 
    DrawMyGraph g; 
    ImageView clock,graph_Text,heart_Index,graph_View; 
    static long startTime = 0; 
    static int beats = 0; 
    volatile boolean show=false; 
    SurfaceHolder sh; 
    SurfaceView sv; 
    TextView show_BPM; 
    Button on,off; 
    int no,count=0; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    show_BPM=(TextView)findViewById(R.id.showBPM); 
    sv=(SurfaceView)findViewById(R.id.surfaceView1); 
    clock=(ImageView)findViewById(R.id.clock); 
    graph_Text=(ImageView)findViewById(R.id.graphText); 
    heart_Index=(ImageView)findViewById(R.id.heartIndex); 
    graph_View=(ImageView)findViewById(R.id.graphview); 
    graph_Text.setBackgroundResource(R.drawable.graphtext2); 
    on=(Button)findViewById(R.id.on); 
    off=(Button)findViewById(R.id.off); 

    Random r=new Random(); 
    no=r.nextInt(84-60)+60; 

    Context context = getApplicationContext(); 
    CharSequence text = "cover the camera with your index finger......!"; 
    int duration = 100000; 

    Toast toast = Toast.makeText(context, text, duration); 
    toast.show(); 
    /////////////////////////////// 
    //////////////////////////// 



    g = new DrawMyGraph(this, 26); 
    addContentView(g, new LayoutParams(LayoutParams.MATCH_PARENT, 
      LayoutParams.MATCH_PARENT)); 
    startCamPreview(); 



} 

public void startCamPreview() { 
    SurfaceView sv = (SurfaceView) findViewById(R.id.surfaceView1); 
    SurfaceHolder sh = sv.getHolder(); 
    mCamera = Camera.open(); 

    try { 
     mCamera.setPreviewDisplay(sh); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    sh.addCallback(new Callback() { 

     @Override 
     public void surfaceDestroyed(SurfaceHolder holder) { 
      // TODO Auto-generated method stub 
      System.out.println("Deleted"); 
      mCamera.setPreviewCallback(null); 
      mCamera.stopPreview(); 
      mCamera.release(); 
      mCamera = null; 
     } 

     @Override 
     public void surfaceCreated(SurfaceHolder holder) { 
      System.out.println("Created"); 

      mCamera.setPreviewCallback(new PreviewCallback() { 
       public void onPreviewFrame(byte[] data, Camera camera) { 

        Camera.Parameters params = camera.getParameters(); 

        int width = params.getPreviewSize().width; 
        int height = params.getPreviewSize().height; 
        byte[] mYUVData = new byte[data.length]; 
        int[] mRGBData = new int[width * height]; 
        System.arraycopy(data, 0, mYUVData, 0, data.length); 
        decodeYUV420SP(mRGBData, mYUVData, width, height); 
        int[] mRedHistogram = new int[256]; 
        calculateIntensityHistogram(mRGBData, mRedHistogram, 
          width, height, 0); 
        double imageRedMean = 0; 
        double redHistogramSum = 0; 
        for (int bin = 0; bin < 256; bin++) { 
         imageRedMean += mRedHistogram[bin] * bin; 
         redHistogramSum += mRedHistogram[bin]; 
        } // bin 
        imageRedMean /= redHistogramSum; 
        double[] mBinSquared; 
        mBinSquared = new double[256]; 
        for (int bin = 0; bin < 256; bin++) { 
         mBinSquared[bin] = ((double) bin) * bin; 
        } 
        double imageRed2ndMoment = 0; 
        for (int bin = 0; bin < 256; bin++) { 
         imageRed2ndMoment += mRedHistogram[bin] 
           * mBinSquared[bin]; 
        } // bin 
        imageRed2ndMoment /= redHistogramSum; 
        double imageRedStdDev = Math.sqrt((imageRed2ndMoment 
          - imageRedMean * imageRedMean)); 
        int val = (new Double(imageRedStdDev * 100000) 
          .intValue()); 

        show_BPM.setText(String.valueOf(no)); 
        int v = new Double(imageRedStdDev).intValue(); 

        for (int l = 0; l < 1; l++) { 

        } 
        int yVal=250; 
        if (imageRedStdDev < 15 && val != 0) 
        { 
         show=true; 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         float flt=(float)Math.random(); 
         g.addPoint(yVal+flt*25); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         flt=(float)Math.random(); 
         g.addPoint(yVal-flt*20); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         flt=(float)Math.random(); 
         g.addPoint(yVal-flt*30); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         flt=(float)Math.random(); 
         g.addPoint(yVal+flt*35); 
         try { 
          Thread.sleep(500); 
         } catch (InterruptedException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 


        } else { 
         show=false; 
         if(val==0){ 

          count++; 
          g.addPoint(yVal); 
          g.addPoint(yVal); 
          g.addPoint(yVal); 
          g.addPoint(yVal); 
          show_BPM.setText(String.valueOf(0)); 
         }else{ 

         count++; 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         g.addPoint(yVal); 
         show_BPM.setText(String.valueOf(0)); 


         } 
        } 
       } 

      }); 
     } 

     @Override 
     public void surfaceChanged(SurfaceHolder holder, int format, 
       int width, int height) { 
      System.out.println("Changed"); 
      Camera.Parameters parameters = mCamera.getParameters(); 
      parameters.setPreviewSize(320, 240); 
      parameters.setPreviewFrameRate(15); 
      parameters.setSceneMode(Camera.Parameters.SCENE_MODE_NIGHT); 
      parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); 
      mCamera.setParameters(parameters); 
      mCamera.startPreview(); 
      g.invalidate(); 
     } 
    }); 
    // fl.addView(b); 
} 

static public void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width, 
     int height) { 
    final int frameSize = width * height; 

    for (int j = 0, yp = 0; j < height; j++) { 
     int uvp = frameSize + (j >> 1) * width, u = 0, v = 0; 
     for (int i = 0; i < width; i++, yp++) { 
      int y = (0xff & ((int) yuv420sp[yp])) - 16; 
      if (y < 0) 
       y = 0; 
      if ((i & 1) == 0) { 
       v = (0xff & yuv420sp[uvp++]) - 128; 
       u = (0xff & yuv420sp[uvp++]) - 128; 
      } 

      int y1192 = 1192 * y; 
      int r = (y1192 + 1634 * v); 
      int g = (y1192 - 833 * v - 400 * u); 
      int b = (y1192 + 2066 * u); 

      if (r < 0) 
       r = 0; 
      else if (r > 262143) 
       r = 262143; 
      if (g < 0) 
       g = 0; 
      else if (g > 262143) 
       g = 262143; 
      if (b < 0) 
       b = 0; 
      else if (b > 262143) 
       b = 262143; 

      rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) 
        | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); 
     } 
    } 
} 

static public void calculateIntensityHistogram(int[] rgb, int[] histogram, 
     int width, int height, int component) { 
    for (int bin = 0; bin < 256; bin++) { 
     histogram[bin] = 0; 
    } // bin 
    if (component == 0) // red 
    { 
     for (int pix = 0; pix < width * height; pix += 3) { 
      int pixVal = (rgb[pix] >> 16) & 0xff; 
      histogram[pixVal]++; 
     } // pix 
    } else if (component == 1) // green 
    { 
     for (int pix = 0; pix < width * height; pix += 3) { 
      int pixVal = (rgb[pix] >> 8) & 0xff; 
      histogram[pixVal]++; 
     } // pix 
    } else // blue 
    { 
     for (int pix = 0; pix < width * height; pix += 3) { 
      int pixVal = rgb[pix] & 0xff; 
      histogram[pixVal]++; 
     } // pix 


    } 
} 

public void onWindowFocusChanged(boolean hasFocus) { 
    super.onWindowFocusChanged(hasFocus); 
    clock.setBackgroundResource(R.anim.clockanimation); 
    AnimationDrawable clock_Anim=new AnimationDrawable(); 
    clock_Anim=(AnimationDrawable)clock.getBackground(); 
    clock_Anim.start(); 
    timer.start(); 
    } 

CountDownTimer timer=new CountDownTimer(30000,1000){ 

    @Override 
    public void onFinish()throws NullPointerException { 
     // TODO Auto-generated method stub 
     mCamera.stopPreview();**//This is the line for which shows NullPointer exception** 
     g.invalidate(); 
     Canvas.freeGlCaches(); 
     graph_Text.setBackgroundResource(R.drawable.graphtext3); 
     if(count>0) 
     { 
      System.out.println("Hiiiiiii"); 
     show_BPM.setText(String.valueOf(0)); 
     } 
     else 
     { 
      System.out.println("Helllooo"); 
      show_BPM.setText(String.valueOf(no)); 
     } 
    } 

    @Override 
    public void onTick(long arg0) { 
     // TODO Auto-generated method stub 

    } 

}; 

    class DrawMyGraph extends View { 
    public LinkedList<Float> yValues = null; 
    private int size = 0; 
    private LinkedList<Integer> xValues = null; 
    private LinkedList<Long> beatList = new LinkedList<Long>(); 

    public DrawMyGraph(Context context, int size) { 
     super(context); 
     yValues = new LinkedList<Float>(); 
     int inc = 5; 
     this.size = size * inc; 
     xValues = new LinkedList<Integer>(); 

     int cnt = 468; 
     for (int i = 0; i < this.size * inc; i++) { 
      xValues.add(cnt); 
      cnt = cnt - (inc - 2); 
     } 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     Bitmap bitmap=Bitmap.createBitmap(2 , 2, Bitmap.Config.RGB_565); 
     graph_View.setImageBitmap(bitmap); 
     Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     paint.setStyle(Paint.Style.STROKE); 
     paint.setStrokeWidth(2); 
     paint.setColor(Color.RED); 
     invalidate(); 
     for (int i = 0, j = 1; i < yValues.size() && j < yValues.size(); i++, j++) { 


      canvas.drawLine(xValues.get(i) + 30, (yValues.get(i) - 10)*2, 
        xValues.get(j) + 30, (yValues.get(j) - 10)*2, paint); 




     } 
     super.onDraw(canvas); 
} 

    public int getSize() { 
     return size; 
    } 

    public void addPoint(float p) { 
     if (yValues.size() > size) { 
      yValues.removeLast(); 
     } 
     yValues.addFirst(p); 
    } 

    public void addBeat(long beat) { 
     beatList.add(beat); 
    } 

} 
    public void onBackPressed() { 



      finish(); 
      return; 
     } 

} 

這是我的logcat的話

02-10 17:34:25.570:W/dalvikvm(3681):主題ID = 1:螺紋與 未捕獲的異常退出(group = 0x40015578)02-10 17:34:25.574: E/AndroidRuntime(3681):致命異常:main 02-10 17:34:25.574: E/AndroidRuntime(3681):java.lang.NullPointerException 02- 10 17:34:25.574:E/AndroidRuntime(3681):at com.android.ecg.ECG $ 1.onFinish(ECG.java:312)02-10 17:34:25.574: E/Andro idRuntime(3681):at android.os.CountDownTimer $ 1.handleMessage(CountDownTimer.java:118) 02-10 17:34:25.574:E/AndroidRuntime(3681):at android.os.Handler.dispatchMessage(Handler .java:99)02-10 17:34:25.574:E/AndroidRuntime(3681):at android.os.Looper.loop(Looper.java:123)02-10 17:34:25.574: E/AndroidRuntime(3681):at android.app.ActivityThread.main(ActivityThread.java:3687)02-10 17:34:25.574:E/AndroidRuntime(3681):at java.lang.reflect.Method.invokeNative( Native Method)02-10 17:34:25.574:E/AndroidRuntime(3681):at java.lang.reflect.Method.invoke(Method.java:507)02-10 17:34:25.574: E/AndroidRuntime(36 81):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:842) 02-10 17:34:25.574:E/AndroidRuntime(3681):at com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:600)02-10 17:34:25.574:E/AndroidRuntime(3681):在 dalvik.system.NativeStart.main(本機方法)

+1

請重新格式化您的問題。同時粘貼您的NullPointerException。 – Siddharth 2012-02-10 12:21:24

+0

您可以請發佈空指針異常以及 – FabianCook 2012-02-10 12:21:33

+1

我真的希望人們會使用預覽部分來檢查他們的代碼格式... – 2012-02-10 12:22:54

回答

0

歡迎所以。建議不要發佈完整的活動,只要它與NPE一樣「簡單」即可。代碼量很難看清問題。

我想你的計時器在攝像頭準備好之前訪問mCamera對象。在對對象調用方法之前,您應該檢查mCamera是否爲null。另外,請確保在相機準備就緒之前計時器不會啓動。

+0

謝謝,我會照顧下次嘗試的代碼發佈問題 – Ranjit 2012-02-10 12:45:45