Click here to Skip to main content
14,368,111 members
Rate this:
Please Sign up or sign in to vote.
See more:
Is there a better way to store data in csv or excel file which will not replace previous data.i.e when when run emulator, it will write new data at new row

how to get data into the csv file.
generateCsvFile("Example1.csv"); 

    private static void generateCsvFile(String sFileName)
    {
        try
        {
            File root = Environment.getExternalStorageDirectory();
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);

            abc="Guwahati";

            writer.append("Emp_Name");
            writer.append(',');
            writer.append("Adress");
            writer.append('\n');

            writer.append("hussain");
            writer.append(',');
            writer.append("Delhi");
            writer.append('\n');

            //generate whatever data you want

            writer.flush();
            writer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        } 
     }
}

sqlite connection:
db.open();
            db.insertContact(latitude,latitude,heading,time1,imemnumber,speed1,dist,vehicle,start,end);

db.close()
Posted
Updated 8-Jul-13 21:25pm
v2

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Hello Baluleo,

Please use below mentioned constructor for Filewriter.
FileWriter(File file, boolean append)
In your case this will be
FileWriter writer = new FileWriter(gpxfile, true);

Regards,
   
Comments
baluleo 9-Jul-13 3:24am
   
is this constructor export the values from the sqlite database dynamically.
Prasad Khandekar 9-Jul-13 3:33am
   
No. It's just creates a file write and internally open as output stream to the specified file in append mode. Your rest of the code is still required.

Regards,
baluleo 9-Jul-13 4:50am
   
ok thank you, sir. the following code used to write data from sqlite ..
But no response.. can you make me how to resolve this code.

c2 =db.rawQuery("select * from " + DATABASE_TABLE, null);
c2.moveToFirst();
double count2 = c2.getCount();
System.out.println("columns --->" + count2);
final double column1 = c2.getColumnIndex("lat");
final double column2 = c2.getColumnIndex("lon");
final double column3 = c2.getColumnIndex("heading");
final double column4 = c2.getColumnIndex("time");
final double column5 = c2.getColumnIndex("imeinumber");
final double column6 = c2.getColumnIndex("speed");
final double column7 = c2.getColumnIndex("distance");
final double column8 = c2.getColumnIndex("vehicle");
final double column9 = c2.getColumnIndex("start");
final double column10 = c2.getColumnIndex("end"); */
writer.flush();
writer.close();

I called this function in start actionlistener

if (c2 != null) {
do {
double lat = c2.getDouble(1);
double lon = c2.getDouble(2);
double heading = c2.getDouble(3);
double time = c2.getDouble(4);
double imeinumber = c2.getDouble(5);
double speed = c2.getDouble(6);
double distance = c2.getDouble(7);
double vehicle = c2.getDouble(8);
double start = c2.getDouble(9);
double end = c2.getDouble(10);



System.out.println("lat --> "+lat);
System.out.println("lon --> "+lon);
System.out.println("heading--> "+heading);
System.out.println("time --> "+time);
System.out.println("imei --> "+imeinumber);
System.out.println("speed --> "+speed);
System.out.println("distance --> "+distance);
System.out.println("vehicle --> "+vehicle);
System.out.println("start --> "+start);
System.out.println("end --> "+end);
} while(c2.moveToNext());
}

try {
new ExportDatabaseCSVTask().execute("");
} catch(Exception ex) {
Log.e("Error in MainActivity",ex.toString());
}



class ExportDatabaseCSVTask extends AsyncTask<string, void,="" boolean=""> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}

protected Boolean doInBackground(final String... args) {
File dbFile = getDatabasePath("gpstracking.db");
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, "gpstrack.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
Cursor curCSV = db.rawQuery("select * from " + DATABASE_TABLE,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[] ={curCSV.getString(1),curCSV.getString(2),curCSV.getString(3),
curCSV.getString(4),curCSV.getString(5),curCSV.getString(6),curCSV.getString(7),curCSV.getString(8),curCSV.getString(9),curCSV.getString(10)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
Prasad Khandekar 9-Jul-13 5:25am
   
Hello,

I am assuming your using CSVWriter from http://opencsv.sourceforge.net. Change the doInBackground as shown below.

protected Boolean doInBackground(final String... args) {
File dbFile = getDatabasePath("gpstracking.db");
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, "gpstrack.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file, true));
Cursor curCSV = db.rawQuery("select * from " + DATABASE_TABLE,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext()) {
String arrStr[] ={curCSV.getString(1),curCSV.getString(2),curCSV.getString(3),
curCSV.getString(4),curCSV.getString(5),curCSV.getString(6),curCSV.getString(7),curCSV.getString(8),curCSV.getString(9),curCSV.getString(10)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
return true;
}
catch (Exception ex)
{
// Code for exception handlling
}
}

Regards,
baluleo 9-Jul-13 6:20am
   
thanks and Now i tried this code.

DBAdapter.java


package com.example.gpstrack;



import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
class DBAdapter {
public static final String KEY_ROWID = "_id";
public final String tat1 = "lat";
public final String ton1 = "lon";
public final String heading1 = "heading";
public final String time1 = "time";
public final String imeino11 = "imeinumber";
public final String speedval = "speed";
public final String dist1 = "distance";
public final String vehicle1 = "vehicle";
public final String start1 = "start";
public final String end1 = "end";

private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "gpstracking.db";
private static final String DATABASE_TABLE = "contacts";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, "
+ "lat text not null, lon text not null,heading text not null,time text not null" +
",imeinumber text not null,speed text not null,distance text not null,vehicle text not null,start text not null,end text not null);";
private static final CursorFactory factory = null;

private final Context context;

private DatabaseHelper DBHelper;
private static SQLiteDatabase db;

public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}

public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}

public void close() {
DBHelper.close();
}

public long insertContact(String lat, String lon,String heading,String time,String imeinumber,String speed,String distance,String vehicle
,String start,String end) {
ContentValues initialValues = new ContentValues();

initialValues.put(tat1, lat);
initialValues.put(ton1, lon);
initialValues.put(heading1, heading);
initialValues.put(time1, time);
initialValues.put(imeino11, imeinumber);
initialValues.put(speedval, speed);
initialValues.put(dist1, distance);
initialValues.put(vehicle1, vehicle);
initialValues.put(start1, start);
initialValues.put(end1, end);
return db.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deleteContact(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}






ArrayList<string,>> ContentValues(){
ArrayList<string,>> wordList;
wordList = new ArrayList<string,>>();
String selectQuery = "SELECT * FROM DATABASE_TABLE";
// SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<string,> map = new HashMap<string,>();
map.put("lat", cursor.getString(0));
map.put("lon", cursor.getString(1));
map.put("heading", cursor.getString(2));
map.put("time", cursor.getString(3));
map.put("imeinumber", cursor.getString(4));
map.put("speed

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100