3

我制作了一个简单的应用程序,它将记录来自 editText 的用户输入,并将其放入我 sdcard 上的 csv 文件中。现在我的问题是读取该 csv 并将其作为我应用程序下一个活动的变量。

这是我的主要活动:

package com.willardcuizon.differentialgps;

import java.io.File;

import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener{

Button start;
EditText lat;
EditText lon;

LocationListener loclist;
CSVFileWriter csv;
StringBuffer filePath;
File file;


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

    start = (Button) findViewById(R.id.button1);
    start.setOnClickListener(this);

    lat = (EditText) findViewById(R.id.editText1);
    lon = (EditText) findViewById(R.id.editText2);


    filePath = new StringBuffer();
    filePath.append("/sdcard/surveyedGPS.csv");
    file = new File(filePath.toString());

    csv = new CSVFileWriter(file);

}

@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;
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v.getId()==R.id.button1){
        LocationManager locman =        (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        if(locman.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText( getApplicationContext(), "GPS is Enabled.",  Toast.LENGTH_SHORT ).show();
            csv.writeHeader(lat.getText().toString());
            csv.writeHeader(lon.getText().toString());

        }
        else{
            Toast.makeText( getApplicationContext(), "GPS is Disabled.Please enable GPS", Toast.LENGTH_SHORT ).show();   
        }

    }
}





}

这是我的 CSVWriter 类:

package com.willardcuizon.differentialgps;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class CSVFileWriter {

private PrintWriter csvWriter;    
private File file;

public CSVFileWriter(File file) {
this.file = file;

}

public void writeHeader(String data) {

try {
    if (data != null) {

        csvWriter = new PrintWriter(new FileWriter(file, true));
        csvWriter.print(",");
        csvWriter.print(data);
        csvWriter.close();

    }
 } catch (IOException e) {
    e.printStackTrace();
 }

}
}
4

2 回答 2

6

您应该考虑使用这个这个库,因为它将负责编写/解析 csv,并在其值中使用引号作为字符。

于 2013-09-23T05:19:49.850 回答
1

您可以将 csv 文件作为文件打开并尝试逐行读取,然后您可以用逗号分割变量并将它们用于下一个活动。看看这里的答案:

于 2013-09-23T06:21:32.547 回答