Android正在阅读csv

时间:2013-09-23 05:07:24

标签: java android csv

我创建了一个简单的应用程序,它将从editText中记录用户输入,并将它放入我的SD卡上的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();
 }

}
}

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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