I have an app where I get the SQLite db file and send it through email. The thing is, that on some devices the filePath I retrieve with
Context.getDatabasePath(“dbname.db”).getPath()
returns null.
Do I need any special permissions for specific devices? Or is there another way a can retrieve the database file path that will work on all devices.
This is the code I use to get the file and send it:
public synchronized void sendDBMail(String subject, String body,
String sender, String recipients, final DBSender.OnCompletionListener onCompletionListener) throws Throwable {
// Create a default MimeMessage object.
final Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(sender));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText(body);
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
File myDB = FileUtils.copyDBToSD(App.getContext(),BACKUP_DATABASES_DIR, DBHelper.DATABASE_NAME);
String filePath = myDB.getPath();
DataSource source = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(DBHelper.DATABASE_NAME);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
}
public static File copyDBToSD(Context ctx, String sdCardPath, String dataBaseFileName) throws Throwable {
File dataBaseFile = ctx.getDatabasePath(dataBaseFileName);
File dataBaseCopy = FileUtils.createOrReadFileInSDCard(ctx,sdCardPath,dataBaseFileName);
return copyFile(dataBaseFile, dataBaseCopy);
}
Thank you for your help!
Amend your DBHelper
to :-
1) Include a class variable:-
private static String DBPATH;
2) In the constructor after the super call add (assuming context is the variable name of the passed Context, otherwsie change accordingly):-
DBPATH = context.getDatabasePath(DB_NAME).getPath();
3) Add a method:-
public static String getDBPath() {
return DBPATH;
}
4) Then use :-
File dataBaseFile = new File(DBhelper.getDBPath());
Instead of
File dataBaseFile = ctx.getDatabasePath(dataBaseFileName);
You can then do away having the Context within copyDBToSD
's signature.
This, of course does rely upon an instance of DBhelper
having been instantiated. It also assumes that the issue is based upon App.getContext()
being the cause of the issue(s).