ELSheepO
ELSheepO

Reputation: 305

Continuously writing data from different classes to a text file

I have 3 different classes, 1 that monitors the accelerometer data, 1 that tracks GPS and one to write to a file.

I am using this code to write to the file in the accel and GPS class:

GPS

file.write(Latitude + "," + Longitude);

Accel

file.write(sensorEvent.values[0] + ", " + sensorEvent.values[1] + ", " + sensorEvent.values[2]);

Which goes to the write method in the file class;

public void write(String message) {
    try {
        if (out == null) {
            FileWriter datawriter = new FileWriter(file);
            out = new BufferedWriter(datawriter);
        }
        if (file.exists()) {
            out.append(message);
            out.flush();

        }
    } catch (IOException e) {
        Log.e("Error", "fail to write file");
    }
}

The problem I'm having is that its only writing one line with the accel values in it and no GPS.

How do I write the a line that contains both accel and GPS values, and to keep writing those values to the same file.

Upvotes: 0

Views: 1829

Answers (2)

Chuidiang
Chuidiang

Reputation: 1055

new FileWiriter(file) creates a new empty file, so you only get the last line written, all previous lines were removed. You should add the second parameter append=true to the FileWriter constructor

FileWriter datawriter = new FileWriter(file,true);

Upvotes: 4

RelicScoth
RelicScoth

Reputation: 697

You could concat the output of both classes to one string and pass that to your write function:

myString = yourGpsClassExecute
myString += yourAccelExecute
write(myString)

Upvotes: 2

Related Questions