Java – Android: How to store input from edittext to .csv

Android: How to store input from edittext to .csv… here is a solution to the problem.

Android: How to store input from edittext to .csv

I’m new to Android and I have a deep Fortran background. I’ve been trying to make apps and haven’t worked out until now.

I can’t find a way to save the “edittext” field with a button (save) and then save the data entered by this user to a .csv file (preferably in internal storage).

I

found a lot of articles, but everyone turned a blind eye to the basic part I wanted (above).

My best idea is to generate .csv in the class and then create a method to save “edittext” as a new string and then output that string to .csv

Hopefully this can be explained simply, I just can’t find this simple explanation anywhere, or at least I can understand….

Solution

Please try this. I hope this code helps you.

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

}
}

Example Activity .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 the list file

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

Related Problems and Solutions