空指针异常 2D 数组类



我有两个类,MainActivity 和 HjorthClass。

我有一个 nullpointer 异常,我相信它来自我的数组,但我无法弄清楚错误在哪里。

請將您的注意力轉向 MainActivity 中的 TestSeizureDetection()。当我按下调用该方法的按钮时,会出现此问题。我没有包括字符串巨大,因为它包含 7681 个单独的数字。

的基本格式格式

String huge = "1.3870574e+01   2.0512821e+01   3.8485958e+01   4.9816850e+01   6.7789988e+01   6.7789988e+01   6.5836386e+01   7.7557998e+01   8.2246642e+01"

当错误出现时,请参阅下面的 MainActivity、HjorthClass 和相关 LogCat。

主活动

package com.example.android.BluetoothChat;

import android.R.string;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import android.bluetooth.BluetoothSocket;
import android.widget.EditText;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends Activity implements LocationListener{
    Button start, stop;
    Button textData;
    TextView tv;
    TextView tv2;
    TextView sum;
    TextView textResult;
    LocationManager lm;
    static TextToSpeech Talker;
    TextView myLabel;
    Handler mhandler = new Handler();
    int i;
    int sum1 = 0;
    static BluetoothDevice mmDevice;
    static BluetoothAdapter mBluetoothAdapter;
    static BluetoothSocket mmSocket;
    String lat;
    String lon;
    public MyCounter timer;
    public double[][] finalSeizureData= new double[7681][1];
    EditText myTextbox;
    static OutputStream mmOutputStream;
    static InputStream mmInputStream;
    static Thread workerThread;
    static byte[] readBuffer;
    static int readBufferPosition;
    static int counter;
    static volatile boolean stopWorker;
    TextToSpeech talker;
    public HjorthClass testValue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        setTitle("Seizure Detection Helmet Application");
        myTextbox = (EditText)this.findViewById(R.id.name);
        talker = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR)
                {
                talker.setLanguage(Locale.US);
                }
            }
        });
        //if(BluetoothChat.finalValue.returnSum()== true)//TRYING TO USE THE VALUE FROM BLUETOOTH CHAT HERE! ERROR HERE, finalValue cannot be resolved to this variable.
        //{
        //SeizureDetected();
        //}
        //Initialize Counter Sequence
        start = (Button)findViewById(R.id.start);// Launch seishor Sequence
        stop = (Button)findViewById(R.id.stop);//Override Function
        textData =(Button)findViewById(R.id.talk);
        tv  = (TextView)findViewById(R.id.tv);
        tv.setText("30"); // starting from 30.
        sum = (TextView)findViewById(R.id.sum);
        myLabel = (TextView)findViewById(R.id.result);
        textResult = (TextView)findViewById(R.id.TextSeizure);

    final MyCounter timer = new MyCounter(30000,1000);
    final Runnable sumTask = new Runnable()
    {
    @Override
    public void run()
    {
i++;
sum1 = sum1+i;
if(sum1>120)
{
start.setEnabled(true);
    timer.start();
return;
}
sum.setText("Sum:"+sum1);
mhandler.postDelayed(this,1000);
    }
    };


        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v){
            start.setEnabled(false);
            timer.start();
            speakOut();
        }
        });
        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                timer.cancel();
                tv.setText("Emergency Call to first responders prevented");
            }
        });
        textData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v){
                TestSeizureDetected();
        }
        });


        //Initialize GPS layout
        tv2 = (TextView) findViewById(R.id.GPS);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
   public class MyCounter extends CountDownTimer{
        public MyCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onFinish() {
            System.out.println("Timer Completed.");
            tv.setText("Sending information to first responders.");
            String name = myTextbox.getText().toString();
            String textMessage = "Hello my name is "+ name + " Help I need help, I have tonic clonic seizures at latitudinal coordinates " + lat + " and longitudinal coordinates "+ lon; 
            String phoneNumber = "7034004407";
            SmsManager.getDefault().sendTextMessage(phoneNumber, null, textMessage, null, null);

            //phone.setData(Uri.parse("tel:7034004407"));
            //startActivity(phone);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText((millisUntilFinished/1000)+"");
            System.out.println("Timer  : " + (millisUntilFinished/1000));
        }
    }
    @Override
    public void onLocationChanged(Location arg0) 
    {
         lat = String.valueOf(arg0.getLatitude());
         lon = String.valueOf(arg0.getLongitude());
        Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
        tv2.setText("lat="+lat+", long="+lon);
    }
    public void onProviderDisabled(String arg0) {
        Log.e("GPS", "provider disabled " + arg0);
    }
    public void onProviderEnabled(String arg0) {
        Log.e("GPS", "provider enabled " + arg0);
    }
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
    }
    public void SeizureDetected()
    {
        timer.start();
        speakOut();
    }
    public void TestSeizureDetected()
    {
        String[] temp = huge.split("\s+");
        double[] convert = new double[temp.length];
        for(int y = 0; y<convert.length; y++)
        {
            convert[y]= Double.parseDouble(temp[y]);
        }
        for(int i = 0; i<convert.length;i++)
        {
            for(int j = 0; j<1;j++)
            {
                finalSeizureData[i][j] = convert[j];
            }
        }
        testValue = new HjorthClass(finalSeizureData);
        if(testValue.returnSum()== true)
        {
            textResult.setText("Seizure has been detected in Text File");
        }
    }

    public void speakOut()
    {
        String original = ("You will have a seizure in thirty seconds. You will have a seizure shortly. Please arrange yourself in a safe position. You will have a seizure shortly. Please arrange yourself in a safe position. You will have a seizure shortly. Please arrange yourself in a safe position. You will have a seish shortly. Please arrange yourself in a safe position.");
        talker.speak(original, TextToSpeech.QUEUE_FLUSH, null);
    }

}

约斯类

package com.example.android.BluetoothChat;
import android.app.Activity;
public class HjorthClass extends Activity{
public double [][]Active;
public int height;
public int width;
public double [][] d1;
public double [][] d2;
public double [][] m0;
public double [][] threshold;
public double sum;
//check length of height
public HjorthClass (double [][]Active)
{
    height = Active[0].length;
    width = Active[1].length;
    for(int i = 0; i<height; i++)// 1st differential subtracting from previous row
    {
        if(i == 0)
        {
            d1[0][0] = Active[0][0];
        }
        else
        {
          for(int j =0; j < width; j++) 
          {
              d1[i][j] = Active[i][j]-Active[i-1][j];
          }
        }       
    }
    for(int i = 0; i<d1[0].length; i++)// 2nd differential subtracting from the row before
    {
        if(i == 0)
        {
            d2[0][0] = d1[0][0]; //since no previous row -- the difference between the previous row(non-existant) and this row is assumed to be this value
        }
        else
        {
          for(int j =0; j <width; j++)  
          {
              d2[i][j] = d1[i][j]- d1[i-1][j];
          }
        }       
    }
    for(int i = 0; i<height; i++)// Original moving average - is used for Activity
    {
        if(i == 0)
        {
            m0[0][0] = Active[i][i]/2;
        }
        else
        {
          for(int j =0; j < width; j++) 
          {
              m0[i][j] = (Active[i][j]- Active[i-1][j])/2;
          }
        }       
    }
    for(int i = 0; i<m0[0].length; i++)// Threshold, if the value is of the moving average at each data point is greater than 10,000, program outputs 1, otherwise 0
    {
          for(int j =0; j < width; j++) 
          {
            if(m0[i][j] >= 10000 )
            {
              threshold[i][j] = 1;
            }
            else
            {
              threshold[i][j]=0;
            }
          } 
    }   
    for(int i = 0; i<threshold[0].length; i++)// Sum of all the values
    {
          for(int j =0; j < width; j++) 
          {
              sum = sum + threshold[i][j];
          }
    }
}
    public boolean returnSum()
    {
        if(sum >= 300)
        {
            return true;
        }
        else
        return false;
    }

}

日志猫

04-01 17:59:00.836: D/dalvikvm(3506): GC_CONCURRENT freed 90K, 38% free 4146K/6663K, external 2002K/2137K, paused 9ms+2ms
04-01 17:59:01.176: D/dalvikvm(3506): GC_CONCURRENT freed 323K, 36% free 4994K/7751K, external 2002K/2137K, paused 3ms+2ms
04-01 17:59:01.466: D/dalvikvm(3506): GC_CONCURRENT freed 1513K, 45% free 4956K/8903K, external 2002K/2137K, paused 2ms+4ms
04-01 17:59:01.486: D/AndroidRuntime(3506): Shutting down VM
04-01 17:59:01.486: W/dalvikvm(3506): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-01 17:59:01.496: E/AndroidRuntime(3506): FATAL EXCEPTION: main
04-01 17:59:01.496: E/AndroidRuntime(3506): java.lang.NullPointerException
04-01 17:59:01.496: E/AndroidRuntime(3506):     at com.example.android.BluetoothChat.HjorthClass.<init>(HjorthClass.java:27)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at com.example.android.BluetoothChat.MainActivity.TestSeizureDetected(MainActivity.java:236)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at com.example.android.BluetoothChat.MainActivity$5.onClick(MainActivity.java:154)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.view.View.performClick(View.java:2485)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.view.View$PerformClick.run(View.java:9080)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.os.Handler.handleCallback(Handler.java:587)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.os.Looper.loop(Looper.java:130)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at android.app.ActivityThread.main(ActivityThread.java:3683)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at java.lang.reflect.Method.invokeNative(Native Method)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at java.lang.reflect.Method.invoke(Method.java:507)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-01 17:59:01.496: E/AndroidRuntime(3506):     at dalvik.system.NativeStart.main(Native Method)
04-01 17:59:23.046: I/Process(3506): Sending signal. PID: 3506 SIG: 9

在尝试访问d1d2m0threshold数组中的任何值之前,您应该初始化它们。我可能会弄错所需的大小,但您可以尝试以下方法

public HjorthClass (double [][]Active)
{
    height = Active[0].length;
    width = Active[1].length;
    d1 = new double[height][width];
    d2 = new double[height][width];
....

但是,如果您不知道要使用的结构的大小,您可能还希望使用ArrayList<ArrayList<Double>>来保存数据。

你不初始化d1d2,你需要在使用它之前对其进行初始化HjorthClass

看起来您正在将 finalSeizureData(双数组)设置为 covert(单个数组)。 即新的双精度[7681][1] = 新的双精度[温度长度]。所以我认为您的变量 finalSeizureData 将始终包含 1 个单个数组。您没有正确设置数组。我可能需要编写一个快速测试用例...

最新更新