Reputation: 1163
Maybe my question has been asked before, but I couldn't find the proper keyword for searching this.
So I was assigned to develop an update of an application which will be uploaded soon. But I have one big problem. The users who have already installed the previous version may have some data which may be lost when updated. The data is stored in this location
/data/data/app_package_name/shared_prefs/data.xml
I need to browse the text inside the data.xml in order to get required fragments for using them in the new version. How can I check if the application was installed previously and only then read the user data only once when installing the update?
Upvotes: 0
Views: 253
Reputation: 864
In your main activity:
private static final String PRIVATE_PREF = "MainActivity";
private static final String VERSION_KEY = "1";
In onCreate():
init();
init() method:
private void init() {
SharedPreferences sharedPref = getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE);
int currentVersionNumber = 0;
int savedVersionNumber = sharedPref.getInt(VERSION_KEY, 0);
try {
PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
currentVersionNumber = pi.versionCode;
} catch (Exception e) {}
if (currentVersionNumber > savedVersionNumber) {
readData();
Editor editor = sharedPref.edit();
editor.putInt(VERSION_KEY, currentVersionNumber);
editor.commit();
}
}
readData() method - something like:
private void readData() {
StringBuilder sb = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om){
om.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
String result = sb.toString();
}
Make sure you change the VERSION_KEY when you release new app version.
For parsing XML, refer to tutorial
Upvotes: 1