Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : How to remove shared preferences in another package

In my android application I coded to read shared data of another Android application and then to delete that data from shared preferences. My code as follows :

try {

     con = createPackageContext("com.testapp.ws", 0);
     SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
     ipAdr = pref.getString("demostring", "No Value");
     pref.edit().remove("demopref").commit();
   }

This shows following error:

06-12 11:52:07.400: E/ApplicationContext(3587): Couldn't rename file /data/data/com.testapp.ws/shared_prefs/demopref.xml to backup file /data/data/com.testapp.ws/shared_prefs/demopref.xml.bak

I used this method in my other application to make shared data

 public void shareData(){
    String strShareValue = ip;
    SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("demostring", strShareValue);
    editor.commit();
}

How can I do that ? Is there anything to add Manifest file ?

Thanks!

like image 853
Grant Avatar asked Jun 13 '12 18:06

Grant


2 Answers

If you use android:sharedUserId in your manifest files it should work. This is a permissions issue I've been running into myself.

To do this, you simply need to add a tag such as android:sharedUserId="com.example.you" to your <manifest> tag in your AndroidManifest.xml file for both of your applications (and the com.example.you has to be the same in both apps, of course).

Example start of the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="package.name"
    android:versionCode="1"
    android:versionName="1.0"
    android:sharedUserId="com.example.you" >
...

For an indepth description of the way to get this working see my answer on How can I share a SharedPreferences file across two different android apps?

like image 116
matt5784 Avatar answered Oct 20 '22 09:10

matt5784


You need to use MODE_WORLD_READABLE instead of MODE_PRIVATE. Read the docs for further information.

Here's a tutorial to check further if you have any more mistakes.

like image 44
Kazekage Gaara Avatar answered Oct 20 '22 11:10

Kazekage Gaara