简体   繁体   English

Android:如何将edittext的输入存储到.csv

[英]Android: How to store input from edittext to a .csv

Fairly new to android, I come from a heavy fortran background. 相当新的android,我来自一个沉重的fortran背景。 I've been trying to make apps, sucessful until now. 我一直试图制作应用程序,直到现在成功。

I'm having trouble finding a way for: saving an 'edittext' field by use of a button(save), then saving this user inputted data to a .csv file(preferably in internal storage). 我找不到一种方法:通过使用按钮保存“edittext”字段(保存),然后将此用户输入的数据保存到.csv文件(最好是在内部存储器中)。

I've found many articles but everyone glazes over the fundemental part I want(above). 我发现了许多文章,但是每个人都对我想要的基本部分进行了釉面(上图)。

the best idea I've got, is of generating the .csv in the class, then creating a method to save the 'edittext' as a new string, then to output that string to the .csv 我得到的最好的想法是在类中生成.csv,然后创建一个方法将'edittext'保存为新字符串,然后将该字符串输出到.csv

Hopefully this can be simply explained, I just cant find this simple explanation anywhere, or at-least that I can understand... 希望这可以简单解释,我无法在任何地方找到这个简单的解释,或者至少我能理解......

Please try this.I hope this code helps you. 请试试这个。我希望这段代码可以帮到你。

CSVFileWriter.java CSVFileWriter.java

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();
    }

}
}

SampleActivity.java SampleActivity.java

public class SampleActivity extends Activity {
CSVFileWriter csv;
StringBuffer filePath;
File file;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    saveButton = (Button) findViewById(R.id.button1);
    editText = (EditText) findViewById(R.id.editText1);

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

    csv = new CSVFileWriter(file);

    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            csv.writeHeader(editText.getText().toString());

        }
    });
}
}

Add this in manifest file 在清单文件中添加此项

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM