Monday, October 14, 2013

Export android Sqlite database to CSV

you need to add opencsv lib to your project :Open csv Download link
add jar to your app library
Add Permission:
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
CODE:
File dbFile = getDatabasePath("YourDatabase.db");

        DataBaseHelper DBob = new DataBaseHelper(MainActivity.this);


        File exportDir = new File(Environment.getExternalStorageDirectory()

                .getPath(), "");

        if (!exportDir.exists())


        {


            exportDir.mkdirs();


        }


        File file = new File(exportDir, "Filename.csv");


        try


        {


            file.createNewFile();


            CSVWriter csvWrite = new CSVWriter(new FileWriter(file));


            SQLiteDatabase db = DBob.getReadableDatabase();


            Cursor curCSV = db.rawQuery("SELECT * FROM Table_Name", null);


          //  int c = curCSV.getColumnCount();


            csvWrite.writeNext(curCSV.getColumnNames());


            while (curCSV.moveToNext())  {


                String arrStr[] = { curCSV.getString(0), curCSV.getString(1),


                curCSV.getString(2) };


                csvWrite.writeNext(arrStr);


            }

 csvWrite.close();
 curCSV.close();
 }
  catch (SQLException sqlEx)   {
 Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
  }
 catch (IOException e) {
 Log.e("MainActivity", e.getMessage(), e);
 }

2 comments:

  1. This doesnt work to me. I tried many times the same coding. The curCSV.getColumnCOunt() on Android Studio shows in Highlight that can return a NullPointer

    ReplyDelete