Calling the values out from CSV file for aGraphEngine (Android) - android

I am trying to obtain the 4th and 5th elements from the csv data and use it as a dataset for the 2nd (mDatasetNormal) and third graph line. I was able to figure out how to obtain the data from the 3rd element however the rest is an issue.
My questions are:
How to read the Heappy_log.csv and than use the arrayList to obtain data for the graph?
After data is obtained from the csv how to use it for the same graph?
CSV file content:
Aug-30-2014,08:06 AM, 0,0,0
Sep-05-2014,08:09 AM, 0,3,2
Sep-05-2014,08:09 AM, 0,3,2
Whole code:
public class Chart extends Activity {
ArrayList<Integer> stateList = new ArrayList<Integer>();
ArrayList<Integer> normalList = new ArrayList<Integer>();
//Chart creation
private GraphicalView mChart, mChartNormal;
/**
* Create multiple data sets to be used on graph
*/
//Data sets used for graph manipulation
private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeries;
private XYSeriesRenderer mCurrentRenderer;
private XYMultipleSeriesDataset mDatasetNormal = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer mRendere2 = new XYMultipleSeriesRenderer();
private XYSeries mCurrentSeriesNormal;
private XYSeriesRenderer mCurrentRendererNormal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Code which makes activity full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_chart);
readHappyLog();
}
//Create a method for the aChart engine
private void initChart() {
//Series description for both charts
mCurrentSeries = new XYSeries("Amount of happy kids");
mDataset.addSeries(mCurrentSeries);
mCurrentSeriesNormal = new XYSeries("Amount of normal kids");
mDatasetNormal.addSeries(mCurrentSeriesNormal);
//Renderer for happy kids
mCurrentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(mCurrentRenderer);
mRenderer.setAxisTitleTextSize(24);
mRenderer.setYLabelsPadding(20);
mRenderer.setXLabelsPadding(10);
mRenderer.setXTitle(" Date of practice ");
mRenderer.setYTitle(" Number of kids ");
//Renderer for normal kids
mCurrentRendererNormal = new XYSeriesRenderer();
mRendere2.addSeriesRenderer(mCurrentRendererNormal);
mRendere2.setYTitle("Number of normal kids");
//Applying background
mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.BLACK);
mRenderer.setMarginsColor(Color.BLACK);
mRenderer.setPointSize(20);
mRenderer.setShowGrid(true);
mRenderer.setAxesColor(Color.MAGENTA);
mRenderer.setGridColor(Color.MAGENTA);
mRenderer.setPanEnabled(true, true);
mRenderer.setXAxisMin(0.0);
mRenderer.setYAxisMin(0.0);
mRenderer.setLabelsTextSize(24);
//Sets the color of the graph line and width
mCurrentRenderer.setColor(Color.GREEN);
mCurrentRenderer.setLineWidth(10f);
mCurrentRendererNormal.setColor(Color.BLUE);
mCurrentRenderer.setLineWidth(10f);
}
//Add x and y data into the graph and mark the x graph
private void addHappyData(){
Integer x = 0;
for (Integer happy : stateList ){
mCurrentSeries.add(x += 10, happy);
}
}
//Add x and y for normal to the graph
private void addNormalData(){
Integer y = 0;
for (Integer happy : normalList ){
mCurrentSeriesNormal.add(y += 10, happy);
}
}
// Draw the graph
#Override
protected void onResume() {
super.onResume();
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (mChart == null){
initChart();
addHappyData();
addNormalData();
//Set chart type
mChart = ChartFactory.getLineChartView(this, mDataset , mRenderer);
layout.addView(mChart);
mChartNormal = ChartFactory.getLineChartView(this, mDatasetNormal,mRendere2);
layout.addView(mChartNormal);
}else{
mChart.repaint();
mChartNormal.repaint();
}
}
/**
* create a method to read the happy log
*/
private void readHappyLog(){
String FILENAME = "happy_log.csv"; //Open the file name under this string
FileInputStream inputStream = null; // Import the package
String temp;
String[] a;
try {
inputStream = openFileInput(FILENAME); //Open file desceriptor (Object)
byte[] reader = new byte [inputStream.available() ]; //Everything from disk is byte
while (inputStream.read( reader ) != -1 ){}
//Reader array now holds the entire file
//Needs to create scanner in order to read the file properly
Scanner s = new Scanner (new String(reader));
s.useDelimiter(("\\n"));
while (s.hasNext()){
//Split the string lines if he sees comma value
temp = s.next();
a = temp.split(",");
stateList.add(Integer.parseInt(a[2]));
normalList.add(Integer.parseInt(a[3]));
}
s.close();
}catch (Exception e ){
Log.e("Chart", e.getMessage());
}finally {
if (inputStream != null ){
try{ inputStream.close();
} catch (IOException e){
Log.e( "Chart", e.getMessage());
}
}
}
}

Problem solved:
//Add x and y data to series
private void addHappyData() {
Integer x = 0;
for (Integer happy : stateList) {
mCurrentSeries.add(x += 10, happy);
}
}
private void addNormalData() {
Integer x = 0;
for (Integer normal : normalList) {
mNormalSeries.add(x += 10, normal);
}
}
// Draw the graph
#Override
protected void onResume() {
super.onResume();
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
if (mChart == null) {
initChart();
addHappyData();
addNormalData();
//Set chart type
mChart = ChartFactory.getLineChartView(this, mDataset, mRenderer);
layout.addView(mChart);
} else {
mChart.repaint();
}
}
/**
* create a method to read the happy log
*/
private void readHappyLog() {
String FILENAME = "happy_log.csv"; //Open the file name under this string
FileInputStream inputStream = null; // Import the package
String temp;
String[] a;
try {
inputStream = openFileInput(FILENAME); //Open file desceriptor (Object)
byte[] reader = new byte[inputStream.available()]; //Everything from disk is byte
while (inputStream.read(reader) != -1) {
}
//Reader array now holds the entire file
//Needs to create scanner in order to read the file properly
Scanner s = new Scanner(new String(reader));
s.useDelimiter(("\\n"));
while (s.hasNext()) {
//Split the string lines if he sees comma value
temp = s.next();
a = temp.split(",");
stateList.add(Integer.parseInt(a[2]));
normalList.add(Integer.parseInt(a[3]));
}
s.close();
} catch (Exception e) {
Log.e("Chart", e.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Chart", e.getMessage());
}
}
}
}
}

Related

How to read a CSV file?

I am creating an application where i do some real-time image analysis and store them into a csv file. The csv has 2 columns time and y-value of each frame.
I want to read this file and store the values from 2 columns into to double array. I want this because i want to perform an fast Fourier transformation on the data.
public class MainActivity extends AppCompatActivity implements CameraView.PreviewReadyCallback {
private static Camera camera = null;
private CameraView image = null;
private LineChart bp_graph;
private int img_Y_Avg, img_U_Avg, img_V_Avg;
private long end = 0, begin = 0;
double valueY, valueU, valueV;
Handler handler;
private int readingRemaining = 1200;
private static long time1, time2, timeDifference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
bp_graph = (LineChart)findViewById(R.id.graph);
graph_features();
//open camera
try {
camera = Camera.open();
handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
camera.stopPreview();
camera.release();
}
};
handler.postDelayed(runnable, 30000);
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if (camera != null) {
image = new CameraView(this, camera);
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(image);
image.setOnPreviewReady(this);
}
}
#Override
protected void onResume(){
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onPreviewFrame(long startTime, int ySum, int uSum, int vSum, long endTime) {
begin = startTime;
img_Y_Avg = ySum;
img_U_Avg = uSum;
img_V_Avg = vSum;
end = endTime;
showResults(begin, img_Y_Avg, img_U_Avg, img_V_Avg, end);
}
private void showResults(long startTime, int ySum, int uSum, int vSum, long endTime){
//set value of Y on the text view
TextView valueOfY = (TextView)findViewById(R.id.valueY);
//valueY = img_Y_Avg;
valueOfY.setText(String.valueOf(img_Y_Avg));
//start time in milliseconds
long StartDurationInMs = TimeUnit.MILLISECONDS.convert(begin, TimeUnit.MILLISECONDS);
ArrayList<Long> startOfTime = new ArrayList<>();
startOfTime.add(StartDurationInMs);
//store value to array list
ArrayList<Integer> yAverage = new ArrayList<>();
yAverage.add(img_Y_Avg);
//convert to readable format
String readableDate = new SimpleDateFormat("MMM dd,yyyy, HH:mm:ss.SSS").format(EndDurationInMs);
Log.d("Date ", readableDate);
Log.d("time ", String.valueOf(String.valueOf(yAverage.size())));
//store when all array are generated
Log.d("time ", String.valueOf(StartDurationInMs));
ArrayList<Long> getValues = new ArrayList<>();
for(int i = 0; i < yAverage.size(); i++) {
getValues.add(startOfTime.get(i));
getValues.add((long)(yAverage.get(i)));
}
//store the yAverage and start time to csv file
storeCsv(yAverage, getValues);
Log.d("MyEntryData", String.valueOf(getValues));
}
public void storeCsv(ArrayList<Integer>yAverage, ArrayList<Long>getValues){
String filename = "temporary.csv";
//File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/bpReader";
//File logDir = new File (directoryDownload, "bpReader"); //Creates a new folder in DOWNLOAD directory
File logDir = new File(path);
logDir.mkdirs();
File file = new File(logDir, filename);
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, true);
//outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < yAverage.size(); i += 2) {
outputStream.write((getValues.get(i) + ",").getBytes());
outputStream.write((getValues.get(i + 1) + "\n").getBytes());
//outputStream.write((getValues.get(i + 2) + ",").getBytes());
//outputStream.write((getValues.get(i + 3) + "\n").getBytes());
}
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readCsv(){
}
}
This is my MainActivity. What I am doing here is getting the data from CameraView class for each frame with the help of an interface that I created. After that im storing the values into a CSV file called temporary.csv.
Issues
I want to read this csv and store the first column(the time) into one double array and the second column(yAverage) into another double array.
I also want to delete the file once i have all the data stored into the into the double array.
How can I do that?
I would suggest youto use an open source library like OpenCSV to get the datafrom the CSV file. When you have the library implemented it's only a matter of iterating through the x and y columns and assign them to an array. With OpenCSV it would look like that. But i would also suggest you an more object orientec approach if the x and y with the same index coords are related to each other.
String csvFile = "/Users/mkyong/csv/country3.csv";
int length = 100; //If you dont know how many entries the csv file has i would suggest to use ArrayList
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(csvFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]);
yCoords[i] = Double.parseDouble(line[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
From the answer given by Lucas, I got the direction to my solution
public void readCsv(){
//set the path to the file
String getPath = Environment.getExternalStorageDirectory() + "/bpReader";
String csvFile = "temporary.csv";
String path = getPath+ "/" + csvFile;
//File file = new File(path, csvFile);
int length = 500;
double[] xCoords = new double[length];
double[] yCoords = new double[length];
CSVReader reader = null;
try {
File myFile = new File (path);
reader = new CSVReader(new FileReader(myFile));
String[] line;
int i = 0;
while ((line = reader.readNext()) != null) {
xCoords[i] = Double.parseDouble(line[0]) ;
yCoords[i] = Double.parseDouble(line[1]);
Log.d("read:: ", "Time: "+String.valueOf(xCoords[i])+" Y: "+String.valueOf(yCoords[i]));
}
myFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
And then i had to add
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6'
to my gradle,, which can be found at MVN repository

FileNotFoundException in Android but File is setup properly, what is wrong?

I am having a problem. When I implemented the following file in this class which when run independently seems to show the properly being read it works and saves the data into the ArrayLists. This the code I have for that class:
MachineLearningInstance.java
public class MachineLearningInstance {
/*
* Setup Arraylist of Iris Items which will be the size of the .data file
*/
private ArrayList<Iris> irisData = new ArrayList<Iris>();
private ArrayList<Iris> trainingArray = new ArrayList<Iris>();
private Context context;
/*
* These are values for the NeuralNetwork Constructor
*/
private final String comma = ",";
private final String irisSetosa = "Iris-setosa";
private final String irisVersicolor = "Iris-versicolor";
private final String irisVirginica = "Iris-virginica";
public MachineLearningInstance(File f, Context context) {
this.context = context;
try {
int noOfRowsInData = 0;
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
try {
lnr.skip(Long.MAX_VALUE);
noOfRowsInData = lnr.getLineNumber();
//System.out.println(noOfRowsInData);
lnr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
irisData = new ArrayList<Iris>();
// While there is another line in inFile.
Scanner inFile = new Scanner(f);
for (int i = 0; i < noOfRowsInData - 1; i++) {
if (inFile.hasNextLine()) {
// Store line into String
String line = inFile.nextLine();
// Partition values into separate elements in array
String[] numbers = line.split(comma);
// Grab values from that line and store it into a Iris ArrayList Item
irisData.add(i, new Iris(i, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]));
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (irisData == null) {
Toast.makeText(context, "IRIS DATA IS NULL!", Toast.LENGTH_LONG);
}
for (int i = 0; i < irisData.size(); i++) {
Toast.makeText(context, irisData.get(i).getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, irisData.get(i).getIrisClassName(), Toast.LENGTH_SHORT).show();
} // Used to check values
//sortData();
}
/*
Initialize method to grab the 2-D array of the Iris items
*/
public ArrayList<Iris> getTestData() {
return irisData;
}
public ArrayList<Iris> getTrainingData() {
return trainingArray;
}
public ArrayList<Iris> sortData() {
trainingArray.addAll(irisData.subList(0, 100));
return trainingArray;
}
}
When I implement the following code into this fragment, I get a NullPointerException which I think is being caused by a FileNotFoundException because I think the file is not being read properly when implemented through a fragment. Here is the code I have for the Fragment:
public class PredictFragment extends Fragment {
private ListView mListView;
private ArrayList<Iris> irisArrayList;
private ArrayList<Iris> trainingSet = new ArrayList<Iris>();
private ArrayList<Iris> testSet = new ArrayList<Iris>();
private MachineLearningInstance machineLearningInstance;
private IrisAdapter irisAdapter;
private FileOutputStream rawFile;
private File rawFileOutput;
/*
MachineLearningInstance to grab data from .data file and sort it into partition arraylists
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.predict_listview, container, false);
rawFileOutput = new File("C:\\iris\\iris.data");
machineLearningInstance = new MachineLearningInstance(rawFileOutput, getActivity());
trainingSet = machineLearningInstance.getTrainingData();
testSet = machineLearningInstance.getTestData();
irisAdapter = new IrisAdapter(getActivity(), testSet);
mListView = (ListView) view.findViewById(R.id.listView);
mListView.setAdapter(irisAdapter);
return view;
}
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.irisclassification, PID: 1675
java.lang.NullPointerException
at >com.irisclassification.PredictFragment.onCreateView(PredictFragment.java:59)
at android.app.Fragment.performCreateView(Fragment.java:1700)
EDIT:
So would using a fileoutstream and then casting it to a file object be the best way to go about this?
I went ahead and bundles the .data file into the raw assets folder in the resources directory, would this be the correct approach to go about getting access to the .data file on the android device?
public FileOutputStream createFile() {
try {
InputStream inputStream = getActivity().getResources().openRawResource(R.raw.iris);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size = 0;
// Read the entire resource into a local byte buffer
byte[] buffer = new byte[1024];
while ((size = inputStream.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
inputStream.close();
buffer = outputStream.toByteArray();
rawFile = new FileOutputStream("iris.data");
rawFile.write(buffer);
rawFile.close();
} catch (IOException e) {
e.printStackTrace();
}
return rawFile;
}
C:\iris\iris.data is not existent in Android. You have to change the path to a file that exists on your device (Reading files may need an additional permission!) or bundle it and use AssetManager to retrieve it at runtime (like Nobu Games wrote).

Android program to convert the SQLite database to excel

I want to change the sqlite database .db file to excel.
But I am not able to find what exactly I have to do. Can anybody please elaborate in a simple way what I have to perform to achieve this task.
By searching on Google, so many links appears, but I am not able to understand the step by step way to do this.
I have followed these links:
1. How to convert excel sheet into database of sqlite in android
2. SQlite database programmatically convert into Excel file format in Android
3. http://opencsv.sourceforge.net/
My solution is to convert the sqlite database into csv in first step then in second step is to convert the csv file to xls and it works fine for me, you will need 2 libraries (opencsv-1.7.jar; poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
I know this question is a little old but it provided me with the answer to the same question. I've cleaned up the code a little and done away with the need to write a csv file altogether by getting my database helper class to return me an ArrayList. Still using Apache POI though.
File folder =new File(Environment.getExternalStorageDirectory()+APP_FILES_PATH);
if(!folder.exists())
{
folder.mkdir();
}
DatabaseHelper dbHelper = DatabaseHelper.getInstance(context);
ArrayList<String[]> exts = dbHelper.getExtinguisherArray(1);
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("extinguishers");
for(int x = 0; x < exts.size(); x++)
{
String[] arr = exts.get(x);
HSSFRow row = sheet.createRow(x);
for(int i = 0; i< arr.length; i++)
{
HSSFCell cell = row.createCell(i);
String data = arr[i];
cell.setCellValue(data);
}
}
FileOutputStream fileOut = new FileOutputStream(Environment.getExternalStorageDirectory()+APP_FILES_PATH+"file.xls");
hwb.write(fileOut);
fileOut.close();
Export Android SqliteDb to CSV format
You need to do these step...
add this jar file opencsv-1.7.jar http://www.java2s.com/Code/Jar/o/Downloadopencsv17jar.htm
And then use this code
public class ExportDatabaseToCSV{
Context context;
public ExportDatabaseToCSV(Context context) {
this.context=context;
}
public void exportDataBaseIntoCSV(){
CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "csvfilename.csv");
try
{
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase();
Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
//Which column you want to export you can add over here...
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
catch(Exception sqlEx)
{
Log.e("Error:", sqlEx.getMessage(), sqlEx);
}
}
}
In addition to #user2324120's answer, and as we're in Android, you can directly add the libs to gradle (and therefore you don't need to download the jars) :
compile 'com.opencsv:opencsv:3.7'
compile 'org.apache.poi:poi:3.14'
I also did it a different way, a way more customisable one (and without useless CSV transition). Here it is, with a few comments :
public static Pair<Boolean, String> exportToXLS(Context context, boolean byAuthor) {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(context.getString(R.string.sheet_name)); // Good for localization
initSheetColumns(context, workbook, sheet, byAuthor);
addBooksToSheet(sheet, byAuthor);
setColumsWidth(sheet);
OutputStream outputStream = new FileOutputStream(new File(Methods.getDownloadsDirectory(), byAuthor ? context.getString(R.string.mylibrary_by_author_xls) : context.getString(R.string.mylibrary_xls)).getAbsolutePath());
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
return new Pair<>(true, context.getString(R.string.database_saved));
} catch (Exception e) {
e.printStackTrace();
return new Pair<>(false, context.getString(R.string.an_error_has_occured_during_xls_file_creation));
}
}
private static void initSheetColumns(Context context, HSSFWorkbook workbook, HSSFSheet sheet, boolean byAuthor) {
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? context.getString(R.string.db_author) : context.getString(R.string.db_title));
cell = row.createCell(1);
cell.setCellValue(byAuthor ? context.getString(R.string.db_title) : context.getString(R.string.db_author));
cell = row.createCell(2);
cell.setCellValue(context.getString(R.string.db_publisheddate));
/*
etc.
*/
boldHeaders(workbook, row);
}
private static void boldHeaders(HSSFWorkbook workbook, HSSFRow row) {
HSSFCellStyle style = workbook.createCellStyle();
/* Do your own style
...
*/
for (int i = 0; i < 8; i++) {
row.getCell(i).setCellStyle(style);
}
}
// Allow data personalisation and localisation if needed
private static void addBooksToSheet(HSSFSheet sheet, boolean byAuthor) {
int i = 1;
List<Book> books = Book.listAll(Book.class); // I use Sugar library here, if you're not just make a simple db query to get your objects
Collections.sort(books, byAuthor ? Book.bookAuthorComparator : Book.bookNameComparator);
for (Book book : books) {
HSSFRow row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? getBookValue(book, true) : book.getTitle());
cell = row.createCell(1);
cell.setCellValue(byAuthor ? book.getTitle() : getBookValue(book, false));
cell = row.createCell(2);
cell.setCellValue(book.getPublishedDate());
/*
etc.
*/
i++;
}
}
private static void setColumsWidth(HSSFSheet sheet) {
for (int i = 0; i < 8; i++) {
sheet.setColumnWidth(i, 255 * getMaxNumCharacters(sheet, i)); // Autosize not working on Android
}
}
// My method to get the max num char, if it can hekp
public static int getMaxNumCharacters(Sheet sheet, int column) {
int max = 0;
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
Cell cell = row.getCell(column);
if (cell != null) {
int nb = cell.getStringCellValue().length();
if (nb > max) {
max = nb;
}
}
}
max = (int) (max * 1.1);
if (max > 255) {
return 255; // max 255 char for width
}
return max;
}
Hope it helps!

How to convert ArrayList<String> to Float[]

I have to retrieve some data from a file to show it in a chart. The function that shows the chart requires he data as float[] whereas the retrieved data is in the form ArrayList<String>.
What is the easiest way to convert ArrayList<String> to float[]?
try {
FileInputStream fIn = context.openFileInput(fileDir+fileName);
InputStreamReader ipsr = new InputStreamReader(fIn);
BufferedReader b = new BufferedReader(ipsr);
ArrayList<String> list_prix = new ArrayList<String>();
String ligne;
while ((ligne = b.readLine()) != null) {
String dtVal = ligne.split(" ")[2];
dtVal = dtVal.substring(0, dtVal.length() - 2);
list_prix.add(dtVal);
}
//just here if i can convert list_prix to float[]
fIn.close();
ipsr.close();
}
catch (Exception e)
{
Log.e("blah", "Exception", e);
}
Thank you for your help.
I think the following will do it using Guava...
Collection<Float> floats = Collections2.transform(list_prix, new Function<String, Float>() {
public Float apply(String input) {
return Float.parseFloat(input);
}
});
Float[] floatArray = new Float[floats.size()];
floats.toArray(floatArray);
You can loop and use Float.parseFloat().
float [] floatValues = new float[list_prix.size()];
for (int i = 0; i < list_prix.size(); i++) {
floatValues[i] = Float.parseFloat(list_prix.get(i));
}
Now, this assumes that every string in your ArrayList can actually be parsed into a float. If not, it could throw an exception, so you may want to do this in a try/catch block if you are not sure.

Add value from Array to an XY Series

I want to add a value from SQLite to an XY series to create a diagram. Here is what I've done so far:
Double a, b;
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
ArrayList x = new ArrayList();
ArrayList y = new ArrayList();
notesCursor.moveToFirst();
for(int i = 0; i<notesCursor.getCount();i++){
a = notesCursor.getDouble(notesCursor.getColumnIndex(mDbHelper.KEY_ROWID));
b = notesCursor.getDouble(notesCursor.getColumnIndex(mDbHelper.KEY_RESULT));
}
x.add(a);
y.add(b);
notesCursor.moveToNext();
mCurrentSeries.add(x, y);
if (mChartView != null) {
mChartView.repaint();
}
But I've got a problem at the line:
mCurrentSeries.add(x, y);
How I can add an Array to an XY series? Any suggestions?
not sure what library you are using here to create your diagram (chart?). I use aChartEngine which is pretty good. The code I use to get a dataset containing a time series in aChartEngine is:
public static XYMultipleSeriesDataset getDemoDataset(Cursor c,
String title, String... columnName) {
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
TimeSeries series = new TimeSeries(title);
try {
if (c.moveToFirst()) {
do {
int mins = c.getInt(c.getColumnIndex(columnName[0]));
java.util.Date date =null;
try{
date = DateFactory.stringToDate(c.getString(c.getColumnIndex(columnName[1])));
}catch(Exception e){
}
if(date==null){
continue;
}
series.add(date, mins);
} while (c.moveToNext());
} else {
Log.d(TAG, "There were no values in the cursor.");
}
} finally {
Log.d(TAG, "finally from getDemoDataset being called");
c.close();
}
dataset.addSeries(series);
return dataset;
}

Categories

Resources