Skip to main content

Android Export Sqlite Database

Simple and straight forward code to use directly to export the SQLite database.
Here’s the code to export your android Sqlite Database to CSV file.
Please note that is code is to export sqlite database to CSV file and its done on a button click listener. I am not explaining how to make a button or the Database in android here. As I guess that if you are reading this, you are pretty much ready with your database itself. So Cheers 😉 😉
btnexport = (Button) findViewById(R.id.btnexport); //my button with ID btnexport

		btnexport.setOnClickListener(new View.OnClickListener() {
			SQLiteDatabase sqldb = controller.getReadableDatabase(); //My Database class
			Cursor c = null;

			@Override
			public void onClick(View v) { //main code begins here
				try {
					c = sqldb.rawQuery("select * from places", null);
					int rowcount = 0;
					int colcount = 0;
					File sdCardDir = Environment.getExternalStorageDirectory();
					String filename = "MyBackUp.csv";
                                        // the name of the file to export with
					File saveFile = new File(sdCardDir, filename);
					FileWriter fw = new FileWriter(saveFile);

					BufferedWriter bw = new BufferedWriter(fw);
					rowcount = c.getCount();
					colcount = c.getColumnCount();
					if (rowcount > 0) {
						c.moveToFirst();

						for (int i = 0; i < colcount; i++) {
							if (i != colcount - 1) {

								bw.write(c.getColumnName(i) + ",");

							} else {

								bw.write(c.getColumnName(i));

							}
						}
						bw.newLine();

						for (int i = 0; i < rowcount; i++) {
							c.moveToPosition(i);

							for (int j = 0; j < colcount; j++) {
								if (j != colcount - 1)
									bw.write(c.getString(j) + ",");
								else
									bw.write(c.getString(j));
							}
							bw.newLine();
						}
						bw.flush();
						infotext.setText("Exported Successfully.");
					}
				} catch (Exception ex) {
					if (sqldb.isOpen()) {
						sqldb.close();
						infotext.setText(ex.getMessage().toString());
					}

				} finally {

				}

			}
		});


Comment below if you have any questions or just type Thanks to let me know, this post was useful to you.

  • Jawad Usman

    can you please send complete code jawafacer@gmail.com

  • krishnakanth goud

    Hi Hitesh Vikani,
    Thanks for the code but, if file name name exists? then what is the next procedure.

    • Take a textbox in your Activity and value of that textbox will be the filename

      • krishnakanth goud

        it is not unique and i am asking if file name is same then it override the content or continue in the same file

        • Yes It will override the current file.

          • krishnakanth goud

            Thank you

  • Ali Shaheen

    Thanks alot 🙂
    you save a mine whole day

  • Mitchell Scott

    2 questions;
    How would I select a specific table withing my database to export.

    and I’m getting an error for the controller.getReadableDatabase part of the code. Should that be initialized anywhere since it can’t resolve?

    Thanks.

    • Like select * from tableName using a cursor.
      You have to first initialize the class object like
      DBController controller = new DBController(this);
      Then you can call any database like
      controller.getWritable
      controller.getReadable

      • Dessy Christin

        im still get the error in getReadableDatabase .

        What should i do ?

        Thanks

  • Tang Weiming

    hi, when i apply your code i get this error, is it something wrong in my manifests?
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dm.zbar.android.examples/com.dm.zbar.android.examples.MainActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    at android.app.ActivityThread.access$600(ActivityThread.java:141)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at com.dm.zbar.android.examples.MainActivity$3.(MainActivity.java:106)
    at com.dm.zbar.android.examples.MainActivity.onCreate(MainActivity.java:104)
    at android.app.Activity.performCreate(Activity.java:5104)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    at android.app.ActivityThread.access$600(ActivityThread.java:141)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

  • Tang Weiming

    hi, i get this error when i click on the export button “open failed : EACCES(permission denied), how can i solve this ?

  • Prem Naik

    hi, i have successfuly exported implementing your code but my sqlite database has date column with Long Integer(20170101000000) data type. how i can export that column in dd-MMM-yyyy format(01-Jan-2017)to csv or xls file.?
    thanks

  • Krithika Manoharan

    hi, Thanks for the code. i have created db in the same java page from where i am exporting the csv. so i dont have a separate dbhelper page. how to call getreadabledatabase in this case? android studio suggestions shows me to create method for it.

    • Dessy Christin

      Hey, i want to ask you something about Android Export Sqlite Database. The code is placed in which class ? Thank you for you question…

  • Dessy Christin

    Can you send complete code to me by gmail dessychristin56@gmail.com.
    Thanks

  • Nur Singgih Abu Ats-Tsaaqib

    can you please send complete code nur.singgih.programmer@gmail.com