Database won't remove when uninstall the Android Application - android

I have two major questions.
Database won't delete when uninstall app.
Downloaded files won't delete while unstable the app.
There is a database in my android application. I create it by java
class as follows.
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_QUOTES);
db.execSQL(CREATE_TABLE_FILTERS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUOTES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUOTES);
// create new tables
onCreate(db);
}
There is no specific path defined at the code for database.
This is the code how I download files. And there is specific path, But it is not allowed to create folder in Android>data>com.myapp as well.
public String downloadImage(String img_url, int i) {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/fog/images/filters");
// Make sure the Pictures directory exists.
dir.mkdirs();
File destinationFile = new File(dir, "filter"+i);
String filepath = null;
try{
URL url = new URL("http://fog.wrapper.io/uploads/category/"+img_url+".png");
HttpURLConnection conection = (HttpURLConnection)url.openConnection();
conection.setRequestMethod("GET");
conection.setRequestProperty("Content-length", "0");
conection.setUseCaches(false);
conection.setAllowUserInteraction(false);
conection.connect();
int status = conection.getResponseCode();
switch (status) {
case 200:
case 201:
FileOutputStream fileOutput = new FileOutputStream(destinationFile);
InputStream inputStream = conection.getInputStream();
int totalSize = conection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength; Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath = destinationFile.getPath();
Log.i("filepath:"," "+filepath) ;
return filepath;
}
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}
} // Get filters
Please help me. Sorry for bad English.

in Android 6.0, google added new feature called Auto Backup.
when this option is on(default is on), Android system copies almost every directories and files that created by system, and upload it to user's google drive account.
When user reinstalls app, android automatically restore app's data, no matter how it was installed(via Play store, adb install, initial device setup).
The restore operation occurs after the APK is installed, but before the app is available to be launched by the user.
android developers page :
https://developer.android.com/guide/topics/data/autobackup.html

GUI WAY
If this is a personal account and you need to delete the backup for testing, you can go to drive.google.com for your account and navigate to the backups section.
Select a backup and you are given the option to delete the backups for a specific device:
ADB SHELL WAY
You can also do this from the command line with the following:
adb shell bmgr wipe com.google.android.gms/.backup.BackupTransportService com.example.app
You can find more details related to this command here:
http://www.androiddocs.com/tools/help/bmgr.html#other
ADB SHELL BACKUP MANAGER USAGE
The usage for the command can be found here:
https://github.com/aosp-mirror/platform_frameworks_base/blob/6f357d3284a833cc50a990e14b39f389b8972254/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java#L443
System.err.println("usage: bmgr [backup|restore|list|transport|run]");
System.err.println(" bmgr backup PACKAGE");
System.err.println(" bmgr enable BOOL");
System.err.println(" bmgr enabled");
System.err.println(" bmgr list transports");
System.err.println(" bmgr list sets");
System.err.println(" bmgr transport WHICH");
System.err.println(" bmgr restore TOKEN");
System.err.println(" bmgr restore TOKEN PACKAGE...");
System.err.println(" bmgr restore PACKAGE");
System.err.println(" bmgr run");
System.err.println(" bmgr wipe TRANSPORT PACKAGE");
System.err.println("");
System.err.println("The 'backup' command schedules a backup pass for the named package.");
System.err.println("Note that the backup pass will effectively be a no-op if the package");
System.err.println("does not actually have changed data to store.");
System.err.println("");
System.err.println("The 'enable' command enables or disables the entire backup mechanism.");
System.err.println("If the argument is 'true' it will be enabled, otherwise it will be");
System.err.println("disabled. When disabled, neither backup or restore operations will");
System.err.println("be performed.");
System.err.println("");
System.err.println("The 'enabled' command reports the current enabled/disabled state of");
System.err.println("the backup mechanism.");
System.err.println("");
System.err.println("The 'list transports' command reports the names of the backup transports");
System.err.println("currently available on the device. These names can be passed as arguments");
System.err.println("to the 'transport' and 'wipe' commands. The currently selected transport");
System.err.println("is indicated with a '*' character.");
System.err.println("");
System.err.println("The 'list sets' command reports the token and name of each restore set");
System.err.println("available to the device via the current transport.");
System.err.println("");
System.err.println("The 'transport' command designates the named transport as the currently");
System.err.println("active one. This setting is persistent across reboots.");
System.err.println("");
System.err.println("The 'restore' command when given just a restore token initiates a full-system");
System.err.println("restore operation from the currently active transport. It will deliver");
System.err.println("the restore set designated by the TOKEN argument to each application");
System.err.println("that had contributed data to that restore set.");
System.err.println("");
System.err.println("The 'restore' command when given a token and one or more package names");
System.err.println("initiates a restore operation of just those given packages from the restore");
System.err.println("set designated by the TOKEN argument. It is effectively the same as the");
System.err.println("'restore' operation supplying only a token, but applies a filter to the");
System.err.println("set of applications to be restored.");
System.err.println("");
System.err.println("The 'restore' command when given just a package name intiates a restore of");
System.err.println("just that one package according to the restore set selection algorithm");
System.err.println("used by the RestoreSession.restorePackage() method.");
System.err.println("");
System.err.println("The 'run' command causes any scheduled backup operation to be initiated");
System.err.println("immediately, without the usual waiting period for batching together");
System.err.println("data changes.");
System.err.println("");
System.err.println("The 'wipe' command causes all backed-up data for the given package to be");
System.err.println("erased from the given transport's storage. The next backup operation");
System.err.println("that the given application performs will rewrite its entire data set.");
System.err.println("Transport names to use here are those reported by 'list transports'.");

The auto backup can be disabled by setting android:allowBackup="false" in AndroidManifest.xml

I cam across this question when I was looking for a solution to a similar problem related to GreenDao - slightly more in depth answer here but basically if your on api 23 you'll need to set allowBackup to false to be able to depend on the databases being cleared when you uninstall
https://stackoverflow.com/a/43046256/5298819

Take a look at this SO answer:
What happens to a Sqlite database when app is removed
Does your DB work (aside from not deleting when removing the app)?
If it isn't working properly, you may want to take a look at:
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
Although this is not necessarily related to your issue, you might want to consider creating an open() and close() for your DB and use a SQLiteOpenHelper object in each - in open(), you would use sqliteopenhelperObj.getWriteableDatabase() and in close() you would use sqliteopenhelperObj.close().
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#close
Edit:
If you've downloaded files to your device during the process of testing an app, and you want to delete them, you can use the Device Monitor in Android Studio https://developer.android.com/tools/help/monitor.html There's a file manager that will allow you to see and edit files on your devices. You can also do this on the command line with the ADB (Android Debug Bridge) https://developer.android.com/tools/help/adb.html

Related

How to implement Android’s Data Backup Service

For my Android Project I tried to follow and implement Android Developers Data Backup Guidelines ( http://developer.android.com/guide/topics/data/backup.html ), but Data Backup and Restore doesn't work. Can someone help with examples?
With further investigation I figured out the steps to implement Android Data Backup and Restore. They are:
Add in Manifest xml file the following:
a. android:allowBackup="true" (This enables Android’s Data Backup Service)
b. meta-data android:name="com.google.android.backup.api_key"
android:value=”{Your unique Registration Key for Android Backup Service}” (You must register your application package name with a backup service. To generate a key, go to http://developer.android.com/google/backup/signup.html )
c. android:backupAgent=”.MyBackupAgent” (This is the name of class that implement’s your declared backup agent class). Note1: The first character of the name is a period for the purpose of a shorthand to locate your “com.example.project.MyBackupAgent”. Note2: If a run time Exception occurs (this may or may not happen depending on your project stucture) such as: java.lang.ClassNotFoundException: Didn’t find class “com.example.project.MyBackupAgent” then I suggest you Decompile your apk (Upload your apk package in http://www.decompileandroid.com/ ) and search for the absolute path to your MyBackupAgent and insert this path for android:backupAgent=”{absolute path}.MyBackupAgent”
Here’s an example of a Manifest xml file with Backup support:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.project">
<application android:allowBackup="true" android:backupAgent="md5f576d3976d691fac04b078d1718cab3.MyBackupAgent">
<meta-data android:name="com.google.android.backup.api_key" >android:value="{Your unique Registration Key}" />
</application>
Add in project your MyBackupAgent class. The BackupAgentHelper class provides a convenient wrapper around the BackupAgent class, which minimizes the amount of code you need to write. In your BackupAgentHelper, you must use one or more "helper" objects, which automatically backup and restore certain types of data, so that you do not need to implement onBackup() and onRestore().
Note: Android currently provides backup helpers that will backup and restore complete files from SharedPreferences and internal storage.
Here’s a Java SharedPreferenceBackupHelper example for MyBackupAgent class:
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
import android.util.Log;
public class MyBackupAgent extends BackupAgentHelper{
static final String PREFS = "myprefs";
static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
Log.i("MyFileBackupAgent", "****** Enter BACKUP CLASS *******");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
Log.i("MyFileBackupAgent", "****** Exit BACKUP CLASS ********");
}
}
Here’s a C# Xamarin FileBackupHelper example for MyBackupAgent class:
public class MyBackupAgent: BackupAgentHelper
{
string myProtectData = "File.bin";
string myPersistentData = "Data.bin";
string myDBase = "Database.db";
public override void OnCreate()
{
Console.WriteLine ("****** Enter Backup Files Helpers *********");
base.OnCreate ();
try
{
FileBackupHelper dbkh = new FileBackupHelper (this, myProtectData);
this.AddHelper ("PROTECT_backup", dbkh);
FileBackupHelper persisth = new FileBackupHelper (this, myPersistentData);
this.AddHelper ("PERSIST_backup", persisth);
FileBackupHelper dbh = new FileBackupHelper (this, myDBase);
this.AddHelper ("DATABASE_backup", dbh);
Console.WriteLine ("********* All 3 files backuped *********");
}
catch {
Console.WriteLine ("******* Backup AddHelper Exception ERROR *********");
}
Console.WriteLine ("******** Exit Backup Files Helpers ********");
}
public override void OnBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState)
{
Console.WriteLine ("****** Override OnBackup called ******");
base.OnBackup(oldState, data, newState);
}
public override void OnRestore (BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState)
{
Console.WriteLine ("****** Override OnRestore called ******");
base.OnRestore(data, appVersionCode, newState);
}
}
To perform a backup, your code should make a backup request by calling the dataChanged(). A backup request does not result in an immediate call to your onBackup() method. Instead, the Backup Manager waits for an appropriate time*, then performs backup for all applications that have requested a backup since the last backup was performed. Note, The Backup Manager Service responds every hour as long as at least one DataChanged() was called in-between the hour since the last data backup request.
For test purposes, an immediate backup can be performed with the Android SDK Command Prompt Tool. Try these commands:
To ensure Data Backup Enabled:
adb shell bmgr enable true
To request a Data Backup:
adb shell bmgr backup
To initiate a Data Backup:
adb shell bmgr run
To uninstall your App:
adb uninstall
Then install your App:
adb install
What about your phone device Backup settings? Make sure a WiFi connection is established. Also, under device Settings, make sure "Back up my data" and "Automatic restore" are checked and you have entered in a valid Backup Account email id.
Lastly, to track your Backup upload time stamps, use www.google.com/settings/dashboard (this is your personal google account that matches your google account in your Android phone device Backup settings)

Android app update automatic and silently?

I develop an app and want update itself and want following fetures, device have been rooted :
1 automatic check can update every start (I can do)
2 download the apk file to local (I can do)
3 update with custom dialog, or update silently (I dont know )
edit:
My app run on TV with remote, the default dialog which can control but perfect , so I want use my dialog if there must a dialog.Its best if need not a dialog.
First declare this variables, then call function wherever you want. Then grant superuser, on your superuser application, check the option to always grant, for non user interaction.
#Override
public void onCreate() {
super.onCreate();
//some code...
final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
final String commands = libs + "pm install -r " + "your apk directory"+ "app.apk";
instalarApk(commands);
}
private void instalarApk( String commands ) {
try {
Process p = Runtime.getRuntime().exec( "su" );
InputStream es = p.getErrorStream();
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(commands + "\n");
os.writeBytes("exit\n");
os.flush();
int read;
byte[] buffer = new byte[4096];
String output = new String();
while ((read = es.read(buffer)) > 0) {
output += new String(buffer, 0, read);
}
p.waitFor();
} catch (IOException e) {
Log.v(Debug.TAG, e.toString());
} catch (InterruptedException e) {
Log.v(Debug.TAG, e.toString());
}
}
The regular way (without root and a default installer dialog) is described in another question, and should be used in most cases imho, as I dislike requesting root privileges for a update feature.
There is no difference in providing a custom dialog and installing an apk silently, as both technically are silent installs (e.g. not made by the install activity). With root privileges, you could use a root shell and either replace the apk (as in the open-source keybord manager app) or invoke the package manager from shell. I'd suggest you go for the second way, I linked the keybord manager app source mainly for the root shell creation stuff.
The Android Framework make it defficult to update silently, on custom devices you must call system install service for your apk file, and it will show the install dialog for the user, but if the device is rooted, I think you can make that silently.

Android BackupAgent not working

I am trying to get the BackupAgent working but I can't get it to work. Here is my sample code:
The layout is just a TextView and a Button.
MainActivity:
...
public static final String PREF_NAME = "TestPref";
private static final String TEST_KEY = "TEST";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences pref = getApplicationContext()
.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
if (pref.getString(TEST_KEY, "").length() == 0) {
pref.edit().putString(TEST_KEY, "new Date())
.commit();
new BackupManager(getApplicationContext()).dataChanged();
}
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
if ("START_VALUE".equalsIgnoreCase(tv.getText().toString())) {
tv.setText(pref.getString(TEST_KEY, ""));
}
}
});
}
The BackupHelper is just the ones I available here: http://developer.android.com/reference/android/app/backup/SharedPreferencesBackupHelper.html
I adjusted the name of the pref file with the one I used.
And in the Manifest I added
android:backupAgent="TheBackupAgent" (application tag)
and the backup-meta data
<meta-data android:name="com.google.android.backup.api_key"
android:value="{registered_key}" />
So its really a very simple app.
I am doing the following now:
1)Starting app
2) Textview is initialized with "START_VALUE" in xml file, so I press the Button and the pref-value is displayed
3) I run "adb shell bmgr run" from the console to run the backup immediately
4) I run "adb uninstall com.foo.backuptest"
5) I run "adb install com.foo.backuptest"
Now the value (timestamp) is not restored from the cloud. A new one is generated.
Where is my error??
Your Manifest file needs to include this to turn on Backup:
android:allowBackup="true"
android:backupAgent="TheBackupAgent"
What about your phone Backup settings? Make sure "Back up my data" and "Automatic restore" are checked and you have entered in a valid Backup Account email id.
To know when and how often data is backuped by Google, take a look at this link:
Android backup service - when and how often to backup?
According to this Tester (I also ran a backup frequency test just now): https://advancedweb.hu/2014/12/09/practical_measurement_of_the_android_backup_manager/
The Backup Manager Service responds every hour (I also proved this in my tests) as long as at least one DataChanged() was called in-between the hour since the last data backup request
For a quick test with command line, try these commands:
To ensure Data Backup Enabled: adb shell bmgr enable true
To request a Data Backup: adb shell bmgr backup your.package.name
To initiate a Data Backup: adb shell bmgr run
To uninstall your App: adb uninstall your.package.name
Then install your App: adb install your.package.name

BackupManager Not Calling Backup Transport

Alright, so I'm trying to implement Data Backup into my application, and have been following this guide. I've implemented my BackupAgentHelper using a SharedPreferencesBackupHelper. I don't get any errors, and I'm being sure to call dataChanged() after all preference changes, but when I test the backup (`adb shell bmgr run) I get this information in LogCat:
07-07 12:29:00.258: V/BackupManagerService(291): Scheduling immediate backup pass
07-07 12:29:00.258: V/BackupManagerService(291): Running a backup pass
07-07 12:29:00.258: V/BackupManagerService(291): clearing pending backups
07-07 12:29:00.258: V/PerformBackupTask(291): Beginning backup of 1 targets
07-07 12:29:00.289: V/BackupServiceBinder(291): doBackup() invoked
07-07 12:29:00.289: D/PerformBackupTask(291): invokeAgentForBackup on #pm#
07-07 12:29:00.297: I/PerformBackupTask(291): no backup data written; not calling transport
So for reference, in my manifest I've added:
<application
android:allowBackup="true"
android:backupAgent="com.kcoppock.sudoku.SudokuBackupAgent"
as well as
<meta-data
android:name="com.google.android.backup.api_key"
android:value="my_key_goes_here" />
and my BackupAgentHelper is implemented like so:
public class SudokuBackupAgent extends BackupAgentHelper {
static final String SCORES = "SCORES";
static final String BACKUP_ID = "sudoku_backup";
#Override
public void onCreate() {
SharedPreferencesBackupHelper backupHelper =
new SharedPreferencesBackupHelper(this, SCORES);
addHelper(BACKUP_ID, backupHelper);
}
}
and finally, in my main activity, I call for a data backup like this:
edit.putString(id + "_values", valueCache.toString());
edit.putString(id + "_hints", hintCache.toString());
edit.commit();
BackupManager backup = new BackupManager(this);
backup.dataChanged();
I've tried debugging, and it seems my onCreate() in SudokuBackupAgent is never called. Or at least it's never reached from the debugger. It seems it isn't finding any updated data, and I have double checked to ENSURE there is data to be backed up. Is there something I'm missing here?
EDIT: I should add, I'm testing on a device (Galaxy Nexus), and I've even tried using an exported release APK for testing purposes.
1) Put Log.i() into your onCreate, to see if it's called.
2) Logcat indicates that your function didn't write anything. Check if you have shared_prefs/SCORES file in your app's private folder (assumes using appropriate file manager on rooted device). This is the file you're attempting to have in backup.
Probably your preferences file is something else than this file, in such case fix your String SCORES to reflect real preferences file.
3) I tried to debug BackupAgentHelper.onCreate in my app, and it can be debugged after invoking adb shell bmgt... so it is possible to step here in debugger.
I had the same problem today with Android SDK 4.1. Using 2.3.3 versions, however, helped:
07-15 13:59:56.459: V/LocalTransport(61): performBackup() pkg=com........
07-15 13:59:56.469: V/LocalTransport(61): Got change set key=filehelper:../databases/database.db size=8208 key64=ZmlsZWhlbHBlcjouLi8kYXRhYmFzZXMvZXhwZW5zZXIuZGI=
07-15 13:59:56.469: V/LocalTransport(61): data size 8208
07-15 13:59:56.469: V/LocalTransport(61): finishBackup()
If you do not change your preferences data it will just back up once but not subsequently.
https://developer.android.com/reference/android/app/backup/SharedPreferencesBackupHelper.html
"Whenever a backup is performed, it will back up all named shared preferences that have changed since the last backup operation."
As other poster said make sure to have a log statement in your onCreate.
You can force a backup by:
// bmgr wipe TRANSPORT PACKAGE
bmgr wipe com.google.android.backup/.BackupTransportService com.kcoppock.sudoku
bmgr run
The default is com.google.android.backup/.BackupTransportService, but best to check for yourself with bmgr list transports.
You'll be much happier running against the local transport, not the default Google Transport. Check the dev docs on this.

Android Backup of Shared Preferences to Google Backup Service not working

I've researched and followed how to get my android app to backup the data to google backup so if user loses phone or upgrades to a new phone, they don't lose their data. However, when I test it out (by using the app myself, then uninstalling and reinstalling), no data is restored. Here's what I've done. Perhaps someone can figure out what is wrong.
Applied for a backup key from google
Placed following code in Manifest File (in place of key I did add the key value and for packageName I used my app package name)
android:backupAgent="packageName.MyPrefsBackup">
<meta-data android:name="com.google.android.backup.api_key" android:value="key" />
Created class MyPrefsBackup with following code. The name of the sharedpreference file I want to backup is called UserDB. As far as the PREFS_BACKIP_KEY, I just called it prefs. From what I understand, this is not the same key as the one that goes in the manifest file.
Code:
package packageName;
import android.app.backup.BackupAgentHelper;
import android.app.backup.SharedPreferencesBackupHelper;
public class MyPrefsBackup extends BackupAgentHelper {
// The name of the SharedPreferences file
static final String PREFS = "UserDB";
// A key to uniquely identify the set of backup data
static final String PREFS_BACKUP_KEY = "prefs";
// Allocate a helper and add it to the backup agent
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
Added BackupManager mBackupManager = new BackupManager(this); in my main class where I call the backup manager in next step
Lastly, in my main program I call the backupHelper when data is changed by the following line:
mBackupManager.dataChanged();
Any help is much appreciated.
try new BackupManager(this).dataChanged()
If you are testing this from AVD - you'll need to enable backups - AVD are disabled for backups by default.
adb shell bmgr enable true
Then you can actually debug it to see if the onCreate is called after running
adb shell bmgr run

Categories

Resources