Android application programming: Filling a two-dimensional array in a thread

Viewed 113

I am trying to calibrate an accelerometer, but I can't obtain the 6 sample values at 6 different acceleration readings required for the calibration. PreliminaryW is a double[6][3] array made to fill those sample values. It is 6 by 3 because each acceleration reading has an x, y, and a z component.

I am planning to sample them by pressing a button at the 6 different acceleration readings. This button makes "calibrate" true.

I ofcourse, first make "calibrating" true to start this thread.

For some unfathomable reason, preliminaryW[i] = currentAcc seems to be filling up from 0 to i with the same value instead of just i. I made sure that the currentAcc is different every time I press the "calibrate" button.

What is wrong with my code?

public synchronized void run() {
    Log.d(TAG, "+ in Calibrator thread +");

    int i = -1;
    while (calibrating) {
        if (calibrate) {
            i = i + 1;
            calibrate = false;
            preliminaryW[i] = currentAcc;
            if (i == 5) {
                calibrating = false;
            }
        }
    }
}
1 Answers

I'm not very familiar with the inner-workings of the accelerometer, and it's hard to decide why it's not working without seeing more of the code. For example, can you be sure that there's only one instance of the Thread, or are you creating multiple instances?

Why does this need to be in a Thread?

Looping like that is not good practice either, you should use wait/notify if you absolutely need a Thread. (more info at http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html)

I've drafted a class that does approximately what you want, but doesn't use threading. You could create a Calibrator and then call performCalibration() with each new value:

class Calibrator{
    int count = 0;
    double[][] preliminaryW = new double[6][3];

    public void performCalibration(double[] currentAcc){
        preliminaryW[count] = currentAcc;
        count++;
    }
}

without the Thread and "busy loop", you might be able to omit those flags for 'calibrate' and 'calibrating' which would certainly help debugging as well.

Good Luck!

Related