我怎样才能读取和写入有关在Android上的加速计数据? [英] How can I read and write data about the accelerometer in android?

查看:150
本文介绍了我怎样才能读取和写入有关在Android上的加速计数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写为Android步进计数器。目前,它包括一个活动四个按钮:
一个按钮开始记录存储在一个ArrayList加速度计数据。 ArrayList中需要一个类型的跟踪,这是我来持有一个传感器变化的数据的类。我也有一个停止按钮,和按钮读取或文本文件中写入数据。

这个程序一直给我的ArrayList的一个NullPointerException异常,我无法找出原因。任何帮助将大大AP preciated!

编辑:很抱歉,如果压痕关闭或code不清,这是一所学校分配,我在一个严格的最后期限,所以我要赶去做code可用之前,我可以担心关于可读性和效率。

编辑2:我不再得到任何异常,但我还是不能读/写正确。我能够写入文件中的一个成功,然后以某种方式停止运行。

 包com.myApp.playpool;    //进口公共类MainActivityBAK扩展活动实现SensorEventListener {    //全局字段(痕迹在这里实例化新的ArrayList)    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);        加速=(的TextView)findViewById(R.id.acceleration);
        startButton =(按钮)findViewById(R.id.startButton);
        STOPBUTTON =(按钮)findViewById(R.id.stopButton);
        readButton =(按钮)findViewById(R.id.readButton);
        writeButton =(按钮)findViewById(R.id.writeButton);        SM =(的SensorManager)getSystemService(Context.SENSOR_SERVICE);
        加速度= sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sm.registerListener(这一点,加速度计,SensorManager.SENSOR_DELAY_GAME);        dataFilePath =的getString(R.string.data_file_path);
        acceleration.setText(当前文件:+ dataFilePath);        lastCheck = System.currentTimeMillis的();        defineButtons();    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){        。getMenuInflater()膨胀(R.menu.activity_main,菜单);
        返回true;
    }
    @覆盖
    公共无效onSensorChanged(SensorEvent EVENT1){        如果(运行&放大器;及((System.currentTimeMillis的() - lastCheck)GT 1000)){
            acceleration.setText(X:+ event1.values​​ [0] +\\ NY:+ event1.values​​ [1] +\\ NZ:+ event1.values​​ [2]);
            traces.add(新跟踪(System.currentTimeMillis的(),event1.values​​ [0],event1.values​​ [1],event1.values​​ [2]));
            lastCheck = System.currentTimeMillis的();
        }    }    @覆盖
    公共无效onAccuracyChanged(传感器传感器,精度INT){    }    公共无效defineButtons(){//定义按钮的onClick方法        startButton.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                痕迹=新的ArrayList<跟踪和GT;();
                运行= TRUE;
            }
        });        stopButton.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                痕迹=新的ArrayList<跟踪和GT;();
                运行= FALSE;
            }
        });        readButton.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                尝试{
                    扫描=新的扫描仪(新File(dataFilePath));
                }赶上(FileNotFoundException异常五){
                    e.printStackTrace();
                }
                而(scan.hasNext()){
                    字符串str = scan.nextLine();
                    的String [] =字符串str.split();
                    双倍时间= Double.parseDouble(串[0]);
                    浮X = Float.parseFloat(串[0]),Y = Float.parseFloat(串[1])中,z = Float.parseFloat(串[2]);
                    traces.add(新跟踪(时间,X,Y,Z));
                }                Toast.makeText(getBaseContext(),
                        (读完到S​​D文件:'+ dataFilePath +'),
                        Toast.LENGTH_SHORT).show();
                scan.close();
            }
        });        writeButton.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                尝试{
                    档案文件=新的文件(dataFilePath);
                    打印=的新PrintWriter(文件);
                    file.createNewFile();
                }赶上(FileNotFoundException异常五){
                    e.printStackTrace();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
                的for(int i = 0; I< traces.size();我++){
                    双倍时间= traces.get(我)。时间;
                    浮动X = traces.get(我).X,Y = traces.get(我).Y,Z = traces.get(我).Z;
                    print.println(时间+;+ X +;+ Y +;+ Z +;);
                }
                print.close();
                Toast.makeText(getBaseContext(),
                        (完成写入SD文件:'+ dataFilePath +'),
                        Toast.LENGTH_SHORT).show();
            }
        });    }}

这似乎在被撞毁在写方法循环:

 的for(int i = 0; I< traces.size();我++){


解决方案

这看起来也许像痕迹并没有在被初始化为 onSensorChanged() 或你的 readButton.setOnClickListener ,尽管很难说没有完整的源代码code或堆栈跟踪。如果痕迹是一个全球性//场那么你或许应该初始化它的声明,如:

 保护的ArrayList<跟踪和GT;痕迹=新的ArrayList<跟踪和GT;();

编辑第二个问题

我的猜测是,使用 File.createNewFile()方法不会,如果该文件已经存在工作。也许尝试不同的方法,像这样的例子:

 作家作家=无效;
尝试{
    的OutputStream out = mContext.openFileOutput(dataFileName,Context.MODE_PRIVATE);
    作家=新OutputStreamWriter(出);    的for(int i = 0; I< traces.size();我++){
        双倍时间= traces.get(我)。时间;
        浮动X = traces.get(我).X,Y = traces.get(我).Y,Z = traces.get(我).Z;
        writer.write(时间+;+ X +;+ Y +;+ Z +;);
    }
}
最后{
    如果(作家!= NULL){
        writer.close();
    }
}

I am trying to write a step counter for android. It currently includes four buttons in one activity: a button to start recording accelerometer data which is stored in an arraylist. The arraylist takes a type Trace, which is a class I created to hold the data of one sensor change. I also have a stop button, and buttons to read or write the data from text file.

This program keeps giving me a NullPointerException on the arraylist and I can't figure out why. Any help would be greatly appreciated!

EDIT: Sorry if the indentation is off or the code is unclear, this is a school assignment and I'm on a strict deadline so I have to rush to make the code usable before I can worry about readability or efficiency.

EDIT 2: I no longer get any exceptions, however I still cannot read/write properly. I was able to write to file one successfully, and then somehow it stops functioning.

package com.myApp.playpool;

    //imports

public class MainActivityBAK extends Activity implements SensorEventListener{

    //global fields (traces is instantiated here as new arraylist)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        acceleration=(TextView)findViewById(R.id.acceleration);
        startButton = (Button) findViewById(R.id.startButton);
        stopButton = (Button) findViewById(R.id.stopButton);
        readButton = (Button) findViewById(R.id.readButton);
        writeButton = (Button) findViewById(R.id.writeButton);

        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);

        dataFilePath = getString(R.string.data_file_path);
        acceleration.setText("Current file: " + dataFilePath);

        lastCheck = System.currentTimeMillis();

        defineButtons();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    public void onSensorChanged(SensorEvent event1) {

        if (running && ((System.currentTimeMillis() - lastCheck) > 1000)) { 
            acceleration.setText("X: "+event1.values[0]+"\nY: "+event1.values[1]+"\nZ: "+event1.values[2]);
            traces.add(new Trace(System.currentTimeMillis(), event1.values[0], event1.values[1], event1.values[2]));
            lastCheck = System.currentTimeMillis();
        }

    }

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

    }

    public void defineButtons() { //defines onClick methods for the buttons

        startButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traces = new ArrayList<Trace>();
                running = true;
            }
        });

        stopButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                traces = new ArrayList<Trace>();
                running = false;
            }
        });

        readButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    scan = new Scanner(new File(dataFilePath));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                while (scan.hasNext()) {
                    String str = scan.nextLine();
                    String [] strings = str.split(";");
                    double time = Double.parseDouble(strings[0]);
                    float x = Float.parseFloat(strings[0]), y = Float.parseFloat(strings[1]), z = Float.parseFloat(strings [2]);
                    traces.add(new Trace(time, x, y, z));
                }

                Toast.makeText(getBaseContext(),
                        ("Done reading to SD file: '" + dataFilePath + "'"),
                        Toast.LENGTH_SHORT).show();
                scan.close();
            }
        });

        writeButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    File file = new File(dataFilePath);
                    print = new PrintWriter(file);
                    file.createNewFile();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < traces.size(); i++) {
                    double time = traces.get(i).time;
                    float x = traces.get(i).x, y = traces.get(i).y, z = traces.get(i).z;
                    print.println(time + ";" + x + ";" + y + ";" + z + ";");
                }
                print.close();
                Toast.makeText(getBaseContext(),
                        ("Done writing to SD file: '" + dataFilePath + "'"),
                        Toast.LENGTH_SHORT).show();
            }
        });

    }

}

It seems to be crashing in the for loop in the write method:

for (int i = 0; i < traces.size(); i++) { 

解决方案

It looks perhaps like traces has not been initialized in either onSensorChanged() or in your readButton.setOnClickListener, although it's hard to tell without the full source code or stack trace. If traces is a "// global field" then you should probably initialize it where it's declared, like:

protected ArrayList<Trace> traces = new ArrayList<Trace>();

EDIT for 2nd Question

My guess is that using the File.createNewFile() method won't work if the file already exists. Maybe try a different approach, like this sample:

Writer writer = null;
try {
    OutputStream out = mContext.openFileOutput(dataFileName, Context.MODE_PRIVATE);
    writer = new OutputStreamWriter(out);

    for (int i = 0; i < traces.size(); i++) {
        double time = traces.get(i).time;
        float x = traces.get(i).x, y = traces.get(i).y, z = traces.get(i).z;
        writer.write(time + ";" + x + ";" + y + ";" + z + ";");
    }
}
finally {
    if (writer != null) {
        writer.close();
    }
}

这篇关于我怎样才能读取和写入有关在Android上的加速计数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆