Manasa Reddy
Manasa Reddy

Reputation: 63

Storing Accelerometer Values

I want to develop an app which

  1. Creates a file in external storage

2.Writes accelerometer readings to the file whenever start button is clicked

3.Stops writing when stop button is clicked

4.Reads the contents of the file on the click of read button

I don't know how to create a file in external storage and store the readings of accelerometer in it and later read the values from the file.

I tried the following code in MainACtivity.java

package com.example.startstopbuttonaccelerometerreading;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2;
RelativeLayout layout;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  //get layout
    layout = (RelativeLayout) findViewById(R.id.relative);

    //get textviews
    title=(TextView)findViewById(R.id.name);   
    tv=(TextView)findViewById(R.id.xval);
    tv1=(TextView)findViewById(R.id.yval);
    tv2=(TextView)findViewById(R.id.zval);

    }


public void onStartClick(View view) {
    final SensorEventListener mySensorEventListener = new SensorEventListener() { 
        public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {


        float x = sensorEvent.values[0]; 
        float y = sensorEvent.values[1]; 
        float z = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
        textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
        acc+="\n"+x+ ", "+ y+","+z;

        try {
            File myFile = new File("/sdcard/acc.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(acc);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'acc.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

        }
    }
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            // TODO Auto-generated method stub

        }
    };
    // write on SD card file data in the text box 
    int sensorType = Sensor.TYPE_ACCELEROMETER; 
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

}// onClick
;


public void onStopClick(View view) {
    mSensorManager.unregisterListener(this);
}


@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}



}

This is the activity_main.xml code :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/relative" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="124dp"
        android:text="Start"
        android:onClick="onStartClick" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="37dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Stop"
        android:onClick="onStopClick" />
    <TextView
    android:textSize="30dp"
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

   <TextView
    android:textSize="20dp"
    android:layout_below="@+id/name"
    android:id="@+id/xval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

    <TextView
    android:textSize="20dp"
    android:id="@+id/yval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/xval"
    />

    <TextView
    android:textSize="20dp"
    android:id="@+id/zval"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/yval"
    />

</RelativeLayout>

I wrote the permission in androidmanifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

MainActivity is not getting compiled. The errors are acc and textview cant be resolved. I want to know the code to create a file in external storage and write accelerometer readings to it and read data from the file.

Upvotes: 0

Views: 1878

Answers (2)

Tomas
Tomas

Reputation: 116

I have rewrote your code as the following including AndroidManifest.xml, activity_main.xml and MainActivity.java.

There are three buttons in this program.

1.Start: Start to write three-axis data into acc.txt.

2.Stop: Stop writing data.

3.Read: Read all data in acc.txt

And I create a edit text to show the content in acc.txt after the Read button is clicked. There are some delay time in this program. You can adjust it by yourself.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.so_problem"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.so_problem.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:id="@+id/relative" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="124dp"
        android:text="Start"
        android:onClick="onStartClick" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginLeft="37dp"
        android:layout_toRightOf="@+id/button1"
        android:text="Stop"
        android:onClick="onStopClick" />
    
     <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button2"
        android:layout_centerVertical="true"
        android:text="Read"
        android:onClick="onReadClick" />
     
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="30dp" />

   <TextView
        android:textSize="20dp"
        android:layout_below="@+id/name"
        android:id="@+id/xval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:textSize="20dp"
        android:id="@+id/yval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/xval" />

    <TextView
        android:textSize="20dp"
    android:id="@+id/zval"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/yval" />

    <EditText
        android:id="@+id/showval"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/zval"
        android:layout_alignRight="@+id/zval"
        android:layout_below="@+id/button3"
        android:layout_marginTop="18dp"
        android:clickable="false"
        android:cursorVisible="false"
        android:editable="false"
        android:ems="10"
        android:freezesText="true"
        android:inputType="none"
        android:lines="8"
        android:maxLines="1000"
        android:scrollbars="vertical"
        android:singleLine="false" />

</RelativeLayout>

MainActivity.java

package com.example.so_problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener 
{

    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    TextView title,tvx,tvy,tvz;
    EditText etshowval;
    RelativeLayout layout;
    private String acc;
    private String read_str = "";
    private final String filepath = "/mnt/sdcard/acc.txt";
    private BufferedWriter mBufferedWriter;
    private BufferedReader mBufferedReader;
    private float x;
    private float y;
    private float z;
    
    public static final int MSG_DONE = 1;
    public static final int MSG_ERROR = 2;
    public static final int MSG_STOP = 3;
    
    private boolean mrunning;
    private Handler mHandler;
    private HandlerThread mHandlerThread;
    
    private Handler uiHandler = new Handler(){
        public void handleMessage(Message msg){ 
            String str = (String) msg.obj;
            switch (msg.what)
            {
                case MSG_DONE:
                    Toast.makeText(getBaseContext(), str,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MSG_ERROR: 
                    Toast.makeText(getBaseContext(),str,
                            Toast.LENGTH_SHORT).show();
                    break;
                case MSG_STOP:
                    Toast.makeText(getBaseContext(), str,
                            Toast.LENGTH_SHORT).show();
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
      //get layout
        layout = (RelativeLayout) findViewById(R.id.relative);
    
        //get textviews
        title = (TextView)findViewById(R.id.name);   
        tvx = (TextView)findViewById(R.id.xval);
        tvy = (TextView)findViewById(R.id.yval);
        tvz = (TextView)findViewById(R.id.zval);
        etshowval = (EditText)findViewById(R.id.showval);
        title.setText("Accelerator");
                
        mHandlerThread = new HandlerThread("Working Thread");
        mHandlerThread.start();
        
        mHandler = new Handler(mHandlerThread.getLooper());
        mHandler.post(r);
    }
    
    private Runnable r = new Runnable(){
        @Override
        public void run ()
        {
            while(true)
            {
                if (mrunning)
                {
                    Message msg1 = new Message();
                    try 
                    {
                        WriteFile(filepath,acc);
                        msg1.what = MSG_DONE;
                        msg1.obj = "Start to write to SD 'acc.txt'";
                    } 
                    catch (Exception e) 
                    {
                        msg1.what = MSG_ERROR;
                        msg1.obj = e.getMessage();
                    }
                    uiHandler.sendMessage(msg1);
                }
                else
                {   
                    Message msg2 = new Message();
                    msg2.what = MSG_STOP;
                    msg2.obj = "Stop to write to SD 'acc.txt'";
                    uiHandler.sendMessage(msg2);
                }
                
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    public void onStartClick(View view) 
    {
        start();
    }

    public void onStopClick(View view) 
    {
        stop();
    }
    
    public void onReadClick(View view) 
    {
        etshowval.setText(ReadFile(filepath));
    }
    
    private synchronized void start()
    {
        mrunning = true;
    }
    
    private synchronized void stop()
    {
        mrunning = false;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) 
    {
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) 
    {
        // TODO Auto-generated method stub
    
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
        {
            x = sensorEvent.values[0]; 
            y = sensorEvent.values[1]; 
            z = sensorEvent.values[2]; 
            acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
            
            tvx.setText("X = "+ String.valueOf(x));
            tvy.setText("Y = "+ String.valueOf(y));
            tvz.setText("Z = "+ String.valueOf(z));
        }
    }

    public void CreateFile(String path)
    {
        File f = new File(path);
        try {
            Log.d("ACTIVITY", "Create a File.");
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public String ReadFile (String filepath)
    {
        mBufferedReader = null;
        String tmp = null;
        
        if (!FileIsExist(filepath))
            CreateFile(filepath);
        
        try 
        {
            mBufferedReader = new BufferedReader(new FileReader(filepath));
            // Read string
            while ((tmp = mBufferedReader.readLine()) != null) 
            {
                tmp += "\n";
                read_str += tmp;
            }
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return read_str;
    }
    
    public void WriteFile(String filepath, String str)
    {
        mBufferedWriter = null;
        
        if (!FileIsExist(filepath))
            CreateFile(filepath);
        
        try 
        {
            mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
            mBufferedWriter.write(str);
            mBufferedWriter.newLine();
            mBufferedWriter.flush();
            mBufferedWriter.close();
        }
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public boolean FileIsExist(String filepath)
    {
        File f = new File(filepath);
        
        if (! f.exists())
        {
            Log.e("ACTIVITY", "File does not exist.");
            return false;
        }
        else
            return true;
    }
    
    @Override
    protected void onPause()
    {
    // TODO Auto-generated method stub
        mSensorManager.unregisterListener(this);
        Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
        super.onPause();
    } 
}

Upvotes: 1

Moustafa Alzantot
Moustafa Alzantot

Reputation: 371

 textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;

You didn't declare the "textView" or "acc" variables anywhere

Even after fixing this issue, the code sample you provided above, will end in having a file with only the most recent sensor event records only.. because it creates a new file everytime a sensor event happens, writes the measurements to it, and closes it. When a new measurement is delivered a new file will be created using the same name and so will remove the old entry.

A Good practice to perform that task might be as follows:

  1. Store the file stream as a private variable in your activity
  2. In the start button's click event handler, open the file or create it if not existing .. and store its stream to the private variable of your activity..Also register listener to the accelerometer sensor events.

  3. In the onSensorChanged event, append the new measurements to the file stream

  4. In the stop button's click event handler, unregister the lisetener, and close the file stream.

Upvotes: 0

Related Questions