I want to store 8 integers into a .csv file(the filename will be taken as an input from a EditText) and retrieve them when I want to.
Follow these easy steps to read and edit your CSV file using this app from your phone. Open Google Play Store, search for the CSV Viewer app and install it. Provide the necessary access permissions required for the app. Tap on the CSV Files button to browse through all the CSV files present on your device.
To get the filename you can use this:
EditText fileNameEdit= (EditText) getActivity().findViewById(R.id.fileName);
String fileName = fileNameEdit.getText().toString();
Then write the file on disk:
try {
String content = "Separe here integers by semi-colon";
File file = new File(fileName +".csv");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
To read the file:
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName+".csv"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Then to have the Integers you can use split function:
String[] intArray = sCurrentLine.split(";");
Opencsv doesn't work on Android due to JDK issue.
If you see simular to the following:
05-04 16:13:31.821 25829-25829/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pk.opencsvpoc, PID: 25829 java.lang.NoClassDefFoundError: Failed resolution of: Ljava/beans/Introspector;
It is because Android only ported over a subset of java.beans into its version of java. You can see a list of what is support at https://developer.android.com/reference/java/beans/package-summary
There are plans to switch over to reflection in opencsv 5.0 but I doubt it will remove all our dependencies on java.beans. For now the best suggestion for opencsv is to steer clear of the com.opencsv.bean classes until Android fully supports java.beans or we are successful in removing java.beans.
Another possibility is to try another csv library. I checked apache commons csv and super-csv and apache does not convert to beans but super-csv does using only reflection.
Source: https://sourceforge.net/p/opencsv/wiki/FAQ/#getting-noclassdeffounderror-when-using-android
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With