Site icon ParallelCodes

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.


Exit mobile version