I want to backup data in Android using MyBackUpAgent class which extends BackupAgentHelper. I am using SharedPreferences in order to store data.
My mainactivity code is:
public class MainActivity extends Activity {
EditText inputtext;
TextView outputtext;
Button submit;
public static SharedPreferences sharedprefs;
static final String File_Name_Of_Prefrences ="godplay_preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
init();
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
System.out.println("value="+sharedprefs.getString("Input",""));
outputtext.setText(sharedprefs.getString("Input",""));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
populateUI();
}
});
}
public void populateUI()
{
String savedinput=inputtext.getText().toString();
System.out.println("savedinput="+savedinput);
outputtext.setText(savedinput);
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
Editor editor=sharedprefs.edit();
editor.putString("Input",inputtext.getText().toString());
editor.commit();
requestBackup();
}
private void init() throws ClassCastException
{
inputtext=(EditText) findViewById(R.id.edtInputText);
outputtext=(TextView) findViewById(R.id.txtOutputText);
submit=(Button) findViewById(R.id.btnSubmit);
}
public void requestBackup() {
BackupManager bm = new BackupManager(getApplicationContext());
bm.dataChanged();
}
}
My MyBackUpAgent class:
public class MyBackUpAgent extends BackupAgentHelper{
static final String PREFS_BACKUP_KEY = "backup";
String key_string="Hello World";
#Override
public void onCreate() {
System.out.println("********************");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,MainActivity.File_Name_Of_Prefrences);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
My mainfest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.godplay"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:restoreAnyVersion="false"
android:backupAgent=".MyBackUpAgent"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.godplay.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIhjloadYCTPUNo3yPsSX6LKmziiumZiQVlEEdBA" />
</application>
</manifest>
So far I have tried with bmgr tool to test, it is executing successfully with bmgr tool. However, on testing on Android device and emulator, back up is not happening, nor restoring.
Also, I have tested this on Android 5.1, Android 4.2, and Android 4.0 but still no luck.
It seems to me that my MyBackUpAgent class is never getting called, and I have tried breakpoints in MyBackUpAgent Class and validated it. Its never get hit.
What am I doing wrong?
Docs mention Conditions For Backup Schedule:
The user has enabled backup on the device in Settings > Backup & Reset.
At least 24 hours have elapsed since the last backup.
The device is idle and charging.
The device is connected to a Wi-Fi network. If the device is never connected to a wifi network, then Auto Backup never occurs.
If backup is working for you with bmgr tool but not on a real device / emulator, it's possible you are not meeting all those conditions, therefore backup never occur.
In your AndroidManifest.xml file, try changing
android:backupAgent=".MyBackUpAgent"
with the fully qualified class name, i.e.
android:backupAgent="com.abh.utils.MyBackUpAgent"
but of course changing "com.abh.utils" with the name of the package MyBackUpAgent.java is in.
I had a similar problem and have searched everywhere with no luck. Finally found the solution.
It seems that the BackupAgent needs to be in the top package with no preceding dot. So try changing:
android:backupAgent=".MyBackUpAgent"
to
android:backupAgent="MyBackUpAgent"
You can refer to developer document,
https://developer.android.com/guide/topics/data/backup.html#PerformingBackup
A backup request does not result in an immediate call to your onBackup() method. Instead, the Backup Manager waits for an appropriate time
you can use "bmgr tool" to initiate immediate backup whiling developing your app.
Make sure you call
adb shell bmgr run
to simulate the backup.
Also try using local transport to backup at any time:
adb shell bmgr transport android/com.android.internal.backup.LocalTransport
Related
I'm trying to use SharedPreferencesBackupHelper to save my SharedPreferences value to cloud.
AndroidManifest.xml
<application
android:allowBackup="true"
android:backupAgent=".DataBackupAgent"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIXMH86OqosQlXYuS0QbfyOaZT8fUadY1QUDzo2w" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
DataBackupAgent.java:
public class DataBackupAgent extends BackupAgentHelper {
public static final String PREFS = "data_prefs";
public static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backupManager = new BackupManager(this);
prefs = getSharedPreferences(DataBackupAgent.PREFS, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText)findViewById(R.id.editText);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
Button btnBackup = (Button)findViewById(R.id.button);
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString(DataBackupAgent.PREFS_BACKUP_KEY,text.getText().toString());
edit.commit();
backupManager.dataChanged();
}
});
}
My steps:
Write something at the EditText, click Backup button
Close app and open again. The saved value will be shown in EditText
Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
Edit at 27/02/2015:
I added the following code to restore manually:
backupManager.requestRestore(new RestoreObserver() {
#Override
public void restoreFinished(int error) {
super.restoreFinished(error);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
}
#Override
public void restoreStarting(int numPackages) {
super.restoreStarting(numPackages);
}
#Override
public void onUpdate(int nowBeingRestored, String currentPackage) {
super.onUpdate(nowBeingRestored, currentPackage);
}
});
Unfortunately no callback functions are called.
This means back or auto restore doesn't work at all. Any idea? Thanks
My steps:
1. Write something at the EditText, click Backup button
2. Close app and open again. The saved value will be shown in EditText
3. Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
To test your implementation there are others steps related to the use of bmgras we can see here.
Nevertheless I implemented this feature some days ago and following the steps in the documentation using a real device - Samsung SII - the automatic restore doesn't happen BUT using the emulator all was fine.
Logcat will show you all the operation output details.
IMO, the Android Data Backup feature is not reliable today. We can see some discussion about the implementation problems here and here.
Hope it helps!
I'm trying to implement Data Backup into my application. I build Android 2.2 project, and run in Galaxy s2 4.0.3.
I try to use: BackupManagerTest to save preferences to the cloud
This is my code :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.amdroid.backuptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:backupAgent="net.amdroid.backuptest.MyBackupAgent"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name=".BackupManagerTestActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAI7_yf1xqlpltWZPZiKMHVlDgn3nMfgotjUweSUg" />
</application>
</manifest>
MyBackupAgent.java
public class MyBackupAgent extends BackupAgentHelper {
// The names of the SharedPreferences groups that the application maintains. These
// are the same strings that are passed to getSharedPreferences(String, int).
static final String PREFS_TEST = "testprefs";
// An arbitrary string used within the BackupAgentHelper implementation to
// identify the SharedPreferenceBackupHelper's data.
static final String MY_PREFS_BACKUP_KEY = "myprefs";
// Simply allocate a helper and install it
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, PREFS_TEST);
addHelper(MY_PREFS_BACKUP_KEY, helper);
Log.d("Test", "Adding backupagent...");
}
}
My Activity
public class BackupManagerTestActivity extends Activity {
private SharedPreferences prefs;
private Editor edit;
private BackupManager backupManager;
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backupManager = new BackupManager(getBaseContext());
prefs = getSharedPreferences(MyBackupAgent.PREFS_TEST, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText) findViewById(R.id.editName);
String nome = prefs.getString("KEY_NAME", "");
text.setText(nome);
Button button = (Button) findViewById(R.id.buttonSave);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
edit.putString("KEY_NAME", text.getText().toString());
edit.commit();
Log.d("Test", "Calling backup...");
backupManager.dataChanged();
}
});
}
}
So MyBackupAgent never called. I don't know the reason.
When you call backupManager.dataChanged(), it merely schedules your app for backup. It does not mean your backup helper is called right away.
From http://developer.android.com/guide/topics/data/backup.html:
You can request a backup operation at any time by calling dataChanged(). This method notifies the Backup Manager that you'd like to backup your data using your backup agent. The Backup Manager then calls your backup agent's onBackup() method at an opportune time in the future. Typically, you should request a backup each time your data changes (such as when the user changes an application preference that you'd like to back up). If you call dataChanged() several times consecutively, before the Backup Manager requests a backup from your agent, your agent still receives just one call to onBackup().
Note: While developing your application, you can request a backup and initiate an immediate backup operation with the bmgr tool.
Instructions for the bmgr tool can be found at:
http://developer.android.com/tools/help/bmgr.html
To force all pending backup operations to run immediately, use:
adb shell bmgr run
I am new to RoboGuice and I am trying to set up my activity to use DI. However, nothing happens when I attempt to use it. I only get a blank black window with no content and no logging in my Activity.onCreate() method after I call "super.onCreate(savedInstanceState);"
See these 2 snippets of code:
public class ClikClokActivity extends RoboActivity{
#Inject
private TileAdapter tileAdapter;
#Inject
private GameLogicService gameLogicService;
#Inject
private GridOperationQueue gridOperationQueue;
private GridView gridView;
#Inject
private Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v(this.getClass().toString(), "Entering onCreate");
super.onCreate(savedInstanceState);
Log.v(this.getClass().toString(), "Never logs this with RoboGuice");
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setNumColumns(Constants.GRID_WIDTH);
gridView.setAdapter(tileAdapter);
Log.v(this.getClass().toString(), "GridView initialized");
gridOperationQueue.start();
Log.v(this.getClass().toString(), "Completed onCreate");
}
and
public class ClikClokApplication extends RoboApplication{
#Override
protected void addApplicationModules(List<Module> modules) {
modules.add(new ClikClokModule());
}
}
and
public class ClikClokModule extends AbstractAndroidModule {
#Override
protected void configure() {
}
}
and
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.clikclok"
android:versionCode="1"
android:versionName="1.0">
<application android:name="com.clikclok.ClikClokApplication" android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".ClikClokActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
If you look at the above code, I never get the second logging. However, if I was to extend from Activity instead and remove the android:name="com.clikclok.ClikClokApplication" attribute from my manifest then I do get the second logging (albeit fails with NullPointers as there is no initialization performed).
So what may be happening in super.onCreate(savedInstanceState); that is causing my application not to work?
Thanks
Update from the above:
I've spent quite a bit of time investigating this and using Eclipse's debugger can now see where my code seems to hang within RoboGuice.
The following code is from the InjectorImpl class:
public void injectMembers(Object instance) {
// Reaches here but...
MembersInjector membersInjector = getMembersInjector(instance.getClass());
// ....this comment is never reached
membersInjector.injectMembers(instance);
}
So I dug into the Guice 3.0 code using my debugger and into the FailableCache class:
public V get(K key, Errors errors) throws ErrorsException {
// Reaches here....
Object resultOrError = delegate.get(key);
// ...but not here
if (resultOrError instanceof Errors) {
errors.merge((Errors) resultOrError);
throw errors.toException();
} else {
#SuppressWarnings("unchecked") // create returned a non-error result, so this is safe
V result = (V) resultOrError;
return result;
}
}
How could this be that it just hangs while retrieving a key from a map? I'm not familiar enough with the code and it is quite confusing to troubleshoot.
Any advice is appreciated.
Try to add some bindings in your configure method.
You can also try to inject your grid view like this
#InjectView(R.id.gridview)
GridView gridView;
I hope this will help you.
Regards.
This was caused by me attempting to inject my Activity class into a service class.
So I was attempting to #Inject an instance of "ClikClokActivity" instead of "Activity".
Once I removed this injection attempt, everything worked fine. Not sure if this exposes some other issue with RoboGuice or Guice itself.
I am following this tutorial: link text
Preferences.java:
public class Preferences extends PreferenceActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
PreferencesTutorial.java:
public class PreferencesTutorial extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button prefBtn = (Button) findViewById(R.id.prefButton);
prefBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
}
});
}
}
Preferences.xml:
When application starts, and i click the prefButton, an error occures: "The application PreferencesTutorial (process PreferencesTutorial.com.examples) has stopped unexpectedly. Please try again"
I haven't found any mistakes in the code.
I would also like to show my filestructure if that helps:
AndroidManifest.xml:
What is wrong with the code?
Even if i add (where the cursor is)
<activity
android:name=".Preferences"
android:label="#string/set_preferences">
</activity>
i still get the error.
Try removing this import, if you have it;
import java.util.prefs.Preferences;
You have to mention this in your androidManifest.xml file
<activity
android:name=".Preferences"
android:label="#string/set_preferences">
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
You probably do not have Preferences defined in your manifest.
However, as others have indicated, use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine LogCat and see the stack trace associated with your crash.
Is the error raised in the OnClick in PreferencesTutorial Class or onCreate in the preferences Class? Stick a couple of Log.d("Debug","%ID") in various locations and see which one doesn't get called.
Im trying to do the backing up of my application's data into the Google Servers..
For doing this I've implemented a BackupAgent in my code and I included this in the Android Manifest file and "Meta-data" ( Got after registered my Application's package with the Android Backup Service)
When I run the application to do the backup this is not performing the backup.. Im using Nexus one device (connected to WIFI also) .
Could any one please let me know why it is not calling my BackupAgent's onBackup() method?
Am I missing some thing, to include in the Android manifest file or some where in the program?
The below is my manifest file..
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.simpledatabackup"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:backupAgent="MyBackupAgent"
android:debuggable="true">
<activity android:name=".SimpleDatabackup"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIZn2ysSLR5wNbcq1uaoWQO0HuipMetQENVTsilw" />
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
and the source file is
public class SimpleDatabackup extends Activity {
private SharedPreferences myPrefs ; // Shared Preferences
BackupManager mBackupManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPrefs = this.getSharedPreferences("shared_prefs", MODE_WORLD_READABLE);
SharedPreferences.Editor edit = myPrefs.edit();
edit.putString("firstname", "uday") ;
edit.putString("lastname", "kiran") ;
edit.commit() ;
mBackupManager.dataChanged();
}
}
My Backup Agent is some thing like this: I have not implemented the functionality inside is onBackup() and onRestore(). Once if it is called i will implement what ever i want..
public class MyBackupAgent extends BackupAgent {
#Override
public void onCreate() {
System.out.println("In MyBackuAgent's onCreate() method");
}
#Override
public void onBackup(ParcelFileDescriptor arg0, BackupDataOutput arg1,
ParcelFileDescriptor arg2) throws IOException {
System.out.println("In MyBackuAgent's onBackup()");
// TODO Auto-generated method stub
}
#Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
}
}
In the application tag in the manifest include
android:allowBackup="true"
android:restoreAnyVersion="true"
android:backupAgent="<package>.MyBackupAgent"
Please follow the "Testing your BackupAgent" section to invoke the backup instantly for testing.
BackupManagerService schedules the backup regularly in hour interval after the datachanged call to backupmanager. [grepcode]