how do I add individual strings to a row in CSV file?

176 views Asked by At

I need help with csv, I only started learning how to use it yesterday, and I can't find a solution for that problem. I have a csv file with some array: "name, address, id", using Opencsv. Now I want to be able to add corresponded strings in the row below it. For example, if the user press some button, the name "david" will be added the the csv file, and it will look like:

"name,address,id"
"david"

and when the user will press other button, the adress "3 street" will be added, so it will look like:

"name,address,id"
"david, 3 street"

and so on, so in the end there will the a list of names and their address and id. I just can't figured out how to do it and I cant anything similar. Maybe there is another way to do it?

1

There are 1 answers

0
akash89 On

Let me try to understand what you mean,

In scenario 1, you should have only name added, In scenario 2, you should have name,address added,if that is what I understand?

This is simple and quite achievable. Firstly I am assuming you have already created the row part in your csv and saved to your sd-card

In the next part it should be using an arraylist to write to your csv, check out the code below

String csv = "C:\\work\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));

List<string[]> data = new ArrayList<string[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});

writer.writeAll(data);

writer.close();

Take this arraylist when its your scenario 2.

Also create a separate arraylist which will contain single column data and populate in the same way for scenario 1.

You need to do proper null-checks in scenario 1, else it will throw NullPointer Exception.

Most final approach create two separate methods

Method1- for writing only single column data to your csv.(where you should properly handle the nullchecks)

Method2-the sample code provided For more reference http://www.codeproject.com/Questions/491823/Read-fWriteplusCSVplusinplusplusAndroid

Hope this works.