I\'m working on a proof-of-concept app so that I can implement the feature in a larger app I\'m making. I\'m a bit new to Java and Android Dev but hopefully this shouldn\'t
Try OpenCSV - it will make your life easier.
First, add this package to your gradle
dependencies as follows
implementation 'com.opencsv:opencsv:4.6'
Then you can either do
import com.opencsv.CSVReader;
import java.io.IOException;
import java.io.FileReader;
...
try {
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (IOException e) {
}
or
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
try {
File csvfile = new File(Environment.getExternalStorageDirectory() + "/csvfile.csv");
CSVReader reader = new CSVReader(new FileReader(csvfile.getAbsolutePath()));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "The specified file was not found", Toast.LENGTH_SHORT).show();
}
If you want to package the .csv
file with the application and have it install on the internal storage when the app installs, create an assets
folder in your project src/main
folder (e.g., c:\myapp\app\src\main\assets\
), and put the .csv
file in there, then reference it like this in your activity:
String csvfileString = this.getApplicationInfo().dataDir + File.separatorChar + "csvfile.csv"
File csvfile = new File(csvfileString);
This worked for me in Kotlin. You will need to place the myfile.csv file in the res/raw folder, creating the folder if it isn't there.
val inputStream: InputStream = resources.openRawResource(R.raw.myfile)
val reader = BufferedReader(InputStreamReader(inputStream, Charset.forName("UTF-8")))
reader.readLines().forEach {
//get a string array of all items in this line
val items = it.split(",")
//do what you want with each item
}
With a file named filename.csv in the folder res/raw:
private void gettingItemsFromCSV() {
BufferedInputStream bufferedInputStream = new BufferedInputStream(getResources().openRawResource(R.raw.filename));
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(bufferedInputStream));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.i("Test123", line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is a simple way, which worked for me.
MainActivity.java
// Do not forget to call readWeatherData() in onCreate or wherever you need to :)
// Defining ordered collection as WeatherSample class
private List<WeatherSample> weatherSamples = new ArrayList<>();
private void readWeatherData() {
// Read the raw csv file
InputStream is = getResources().openRawResource(R.raw.data);
// Reads text from character-input stream, buffering characters for efficient reading
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8"))
);
// Initialization
String line = "";
// Initialization
try {
// Step over headers
reader.readLine();
// If buffer is not empty
while ((line = reader.readLine()) != null) {
Log.d("MyActivity","Line: " + line);
// use comma as separator columns of CSV
String[] tokens = line.split(",");
// Read the data
WeatherSample sample = new WeatherSample();
// Setters
sample.setMonth(tokens[0]);
sample.setRainfall(Double.parseDouble(tokens[1]));
sample.setSumHours(Integer.parseInt(tokens[2]));
// Adding object to a class
weatherSamples.add(sample);
// Log the object
Log.d("My Activity", "Just created: " + sample);
}
} catch (IOException e) {
// Logs error with priority level
Log.wtf("MyActivity", "Error reading data file on line" + line, e);
// Prints throwable details
e.printStackTrace();
}
}
WeatherSample.java
public class WeatherSample {
private String month;
private double rainfall;
private int sumHours;
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public double getRainfall() {
return rainfall;
}
public void setRainfall(double rainfall) {
this.rainfall = rainfall;
}
public int getSumHours() {
return sumHours;
}
public void setSumHours(int sumHours) {
this.sumHours = sumHours;
}
@Override
public String toString() {
return "WeatherSample{" +
"month='" + month + '\'' +
", rainfall=" + rainfall +
", sumHours=" + sumHours +
'}';
}
}
As for your source CSV file, first create directory:
app -> res (Right click) -> New -> Android resource directory -> Resource type (raw) -> OK
Then copy and paste your .csv file into that newly appeared directory:
raw (Right click) -> Show in Explorer
Here is the source file I used for the project:
data.csv
If you still have some error, here is a link to the full project:
Source Code
Hope it helps, have fun :)
The following snippet reads a CSV file from the raw
resources folder (which will be packed into your .apk
file upon compilation).
Android by default does not create the raw
folder. Create a raw folder under res/raw
in your project and copy your CSV File into it. Keep the name of the CSV file lower case and convert it into text format when asked. My CSV file name is welldata.csv
.
In the snippet, WellData
is the model class (with constructor, getter and setter) and wellDataList
is the ArrayList
to store the data.
private void readData() {
InputStream is = getResources().openRawResource(R.raw.welldata);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
// Split the line into different tokens (using the comma as a separator).
String[] tokens = line.split(",");
// Read the data and store it in the WellData POJO.
WellData wellData = new WellData();
wellData.setOwner(tokens[0]);
wellData.setApi(tokens[1]);
wellData.setLongitude(tokens[2]);
wellData.setLatitude(tokens[3]);
wellData.setProperty(tokens[4]);
wellData.setWellName(tokens[5]);
wellDataList.add(wellData);
Log.d("MainActivity" ,"Just Created " + wellData);
}
} catch (IOException e1) {
Log.e("MainActivity", "Error" + line, e1);
e1.printStackTrace();
}
}
New coder for Android Studio. I've been researching how to read CSV files and this works best for my needs. (s0, s1, etc. Strings were defined at the beginning of my program).
File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File fileToGet = new File(fileDirectory,"aFileName.csv");
try {
BufferedReader br = new BufferedReader(new FileReader(fileToGet));
String line;
while ((line = br.readLine()) !=null) {
String[] tokens = line.split(",");
s0=tokens[0].toString(); s1=tokens[1].toString(); s2=tokens[2].toString();
s3=tokens[3].toString(); s4=tokens[4].toString(); s5=tokens[5].toString();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}