-2

X and Y two applications. They are not subclass of each other. I want to write a string from X application to Y with SharedPreferences and read it from Y application.

Semra ÖZKAYA
  • 81
  • 2
  • 9
  • 1
    Does this answer your question? [Android: Retrieving shared preferences of other application](https://stackoverflow.com/questions/6030321/android-retrieving-shared-preferences-of-other-application) – a_local_nobody May 27 '20 at 12:16
  • Do you really mean applications? or Activities? Since you mention subclasses.. – RobCo May 27 '20 at 12:20
  • Caution: The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have been deprecated since API level 17. Starting with Android 7.0 (API level 24), Android throws a SecurityException if you use them. If your app needs to share private files with other apps, it may use a FileProvider with the FLAG_GRANT_READ_URI_PERMISSION. For more information, also see Sharing Files. – Semra ÖZKAYA May 27 '20 at 12:24
  • Yes 2 apps. @RobCo – Semra ÖZKAYA May 27 '20 at 12:26

2 Answers2

1

Create Shared preferece data in first application set its mode to MODE_WORLD_READABLE

SharedPreferences mSharedPrefs = getSharedPreferences("Prefs_First", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putString("name", etName.getEditableText().toString());
editor.putString("password", etPassword.getEditableText().toString());
editor.commit();

To access that data from the other app, try this,

Context mContext = createPackageContext("com.sample.globalsharedpreference", CONTEXT_IGNORE_SECURITY);

SharedPreferences firstAppSharedPrefs = mContext.getSharedPreferences("Prefs_First", Context.MODE_WORLD_READABLE);

String strName = firstAppSharedPrefs.getString("name", "");
String strPassword = firstAppSharedPrefs.getString("password", "");

Note that com.sample.globalsharedpreference is the package name of the first app.

0
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.firstapp"
android:versionCode="1"
android:versionName="1.0" 
android:sharedUserId="com.example">

Also you might have to replace Context.MODE_PRIVATE with Context.CONTEXT_RESTRICTED

myContext = context.createPackageContext(
                        "com.example.secondapp",
                        Context.MODE_PRIVATE);
 shared= myContext.getSharedPreferences("fileName", Activity.MODE_PRIVATE);
Hamdy Abd El Fattah
  • 1,405
  • 1
  • 16
  • 16