Click here to Skip to main content
15,940,550 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to back up and restore my SQLite database
I read some online questions and answers but couldn't figure it out yet I read about BackupAgentHelper but I can't understand how it works i also tried FileInputStream but this not working all the time is there any working way or how BackupAgentHelper works?

Edit: i able to restore database successful but I couldn't backup it?

What I have tried:

I tried. This :


final String inFileName = "/data/data/com.aad.lang/databases/ims.db";
		File dbFile = new File(inFileName);
		try{
		FileInputStream fis = new FileInputStream(dbFile);
		String outFileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
					+ "/ims.db";
						// Open the empty db as the output stream
			OutputStream output = new FileOutputStream(outFileName);
		// Transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length;
			try{
			while ((length = fis.read(buffer)) > 0) {
					output.write(buffer, 0, length);
				}
				// Close the streams
				output.flush();
				output.close();
				fis.close();
				}catch(Exception e){
                	}
				}catch (FileNotFoundException e){	
				}


This code doesn't worked all the time?
Posted
Updated 30-May-23 9:05am
v2
Comments
[no name] 30-May-23 23:57pm    
Just do a simple file copy. Nothing special about an SQLite (database) "file".
brahim farhat (AAD) 6-Jun-23 16:08pm    
I just missed to allow permissions in the app after installing
David Crow 3-Jun-23 21:59pm    
I did something akin to this in one of my apps (in response to a button click):
private void backupDatabase()
{
    try
    {
        File sd = Environment.getExternalStorageDirectory();
        if (sd.canWrite()) 
        {
            File file = getDatabasePath("tags.db");
            if (file.exists()) 
            {
                File backupDB = new File(sd, file.getName());
                    
                FileChannel src = new FileInputStream(file).getChannel();                        
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    
                long lBytes = dst.transferFrom(src, 0, src.size());
                    
                src.close();
                dst.close();
    	        	
                Toast.makeText(this, "Database was successfully backed up to the " + sd + " folder.", Toast.LENGTH_LONG).show();
            }
        }
        else
            Toast.makeText(this, "Unable to write to external storage.", Toast.LENGTH_LONG).show();
    } 
    catch (Exception e)
    {
    }
}
brahim farhat (AAD) 6-Jun-23 16:09pm    
Thanks add an answer or solution..

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900