So am developing android application for storing sensor values in one file. My main problem is that app is just writing last value in file. Basically am trying to write code which will store every sensor value to file. Am begginer in writing Android apps... Can someone please help? Here is the code:
package com.example.hello;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView xAxis, yAxis, zAxis;
private SensorManager sm;
private Sensor mSensor;
final File file = new File(Environment.getExternalStorageDirectory(),
"results.txt");
static FileOutputStream fos;
static OutputStreamWriter myOutWriter;
private String writeString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xAxis = (TextView) findViewById(R.id.xAxis);
yAxis = (TextView) findViewById(R.id.yAxis);
zAxis = (TextView) findViewById(R.id.zAxis);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
try {
fos = new FileOutputStream(file);
myOutWriter = new OutputStreamWriter(fos);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SensorEventListener sensor = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
xAxis.setText("xAxis: " + event.values[0]);
yAxis.setText("yAxis: " + event.values[1]);
zAxis.setText("zAxis: " + event.values[2]);
String test = new String(" " + event.values[0] + " "
+ event.values[1] + " " + event.values[2]);
writeData(test);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
sm.registerListener(sensor,
sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_UI);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static void writeData(String test) {
try {
myOutWriter.append(test);
myOutWriter.flush();
myOutWriter.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
}
No comments:
Post a Comment