Android Database Table export to CSV – Part 3


I tried out the method mentioned here. Soon I found out that this was not the thing that I needed .

I needed the table level data which had the transactional information and not database level data.

So CSV was a good option.

In Android phones you can view the csv file in an excel format using ThinkFree Office tools. Similarly in PC using MSOffice Excel.

The code structure is similar to the export to DB as used in the previous post, the difference is that we use a thrid-party Java CSV library called OPENCSV.

/*******************************************************************************
********************************************************************************
Export Database into CSV Class
********************************************************************************
*******************************************************************************/
    class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> 
    {
        private final ProgressDialog dialog = new ProgressDialog(ctx);

        // can use UI thread here
        @Override
        protected void onPreExecute() 
        {
            this.dialog.setMessage("Exporting database...");
            this.dialog.show();
        }   

        // automatically done on worker thread (separate from UI thread)
        protected Boolean doInBackground(final String... args) 
        {
            File dbFile=getDatabasePath("excerDB.db");
            DbClass DBob = new DbClass(MainActivity.this);
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");        
            if (!exportDir.exists()) 
            {
                exportDir.mkdirs();
            }
            File file = new File(exportDir, "excerDB.csv");
            try 
            {
                file.createNewFile();                
                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                SQLiteDatabase db = DBob.getReadableDatabase();
                Cursor curCSV = db.rawQuery("SELECT * FROM ExcerTable",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();
                return true;
            }
            catch(SQLException sqlEx)
            {
                Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
                return false;                
            }
            catch (IOException e) 
            {
                Log.e("MainActivity", e.getMessage(), e);
                return false;
            }
        }
        // can use UI thread here
        @Override
        protected void onPostExecute(final Boolean success) 
        {
            if (this.dialog.isShowing()) 
            {
                this.dialog.dismiss();
            }
            if (success) 
            {
                Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
            } 
            else 
            {
                Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
            }
        }
    }

 

This is used with a button Listener as follows –

Context ctx = MainActivity.this;
//Create a Button listener for the CSV Export
Button impCSVBtn = (Button) findViewById(R.id.imp_csv_id);
impCSVBtn.setOnClickListener(new OnClickListener() {

    public void onClick(View view)
    {

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

This solved the export data problem for my app.

 

References :

http://stackoverflow.com ( No specific question but after reading the responses for similar questions I came up with this ).

 

Related Reading :

Android Database Table export to CSV – Part 1

Android Database Table export to CSV – Part 2

Advertisements

13 Responses

  1. Finally after countless hours of research I was able to export my tables thanks to your tutorials!!!

    • 03-13 15:09:18.370: E/MainActivity(1102): open failed: EACCES (Permission denied). To convert db file into csv file
      plz help me to solve it..

  2. Thanks! This tutorial was awesome! I’d suggest adding a link for the opencsv .jar file as well

    Now I have to move on to importing from csv…

  3. @rahul or anyone else :can you help me out in using DbClass???..its urgent..

  4. hey is there full project files for this? Newbie of course 🙂

  5. i found error such as:03-13 15:09:18.370: E/MainActivity(1102): open failed: EACCES (Permission denied)

  6. 03-13 15:09:18.370: E/MainActivity(1102): open failed: EACCES (Permission denied)
    plz help me to solve it..

  7. Write this Permission in Manifest

  8. How do you export in ANSI? I don’t want utf

  9. I dont get it… why am i having this kind of error? Could not find class ‘au.com.bytecode.opencsv.CSVWriter’ plz reply asap

  10. Need a Work file.plz Provide us !!!!

  11. dafuq with the context? makes no sense and i’m having an error

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: