-1

I have a broadcast receiver that receives the referrer id from the playstore once an app is installed, this then should be written to a file for when the user first logs in gets sent to my webservice where it will then reward the referrer.

The problem I am facing is that in the activity the SharedPreferences always returns a null for when I attempt to pull the value, however on the receiver I tested by pulling the value straight after pushing it.

What I have tried.

getSharedPreferences("referral", MODE_PRIVATE);

PreferenceManager.getDefaultSharedPreferences(this);

getSharedPreferences(context.getPackageName() + "_preferences", MODE_PRIVATE);

However non of them are working, and at this point not sure what to do anymore, I have also tried answers from the following: getDefaultSharedPreferences in a BroadcastReceiver Shared preferences inside broadcastreceiver Android: using sharedPreferences in a broadcast receiver getDefaultSharedPreferences in a BroadcastReceiver But non works for me.

The receiver

public class ReferralReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();

        String referrerString = extras.getString("referrer");
        SharedPreferences sharedPref = context.getSharedPreferences("referral_pref", MODE_PRIVATE);
        sharedPref.edit().putString("referrer", referrerString).apply();
        Log.e("TEST", "Referrer is: " + referrerString + " | " + sharedPref.getString("referrer","null" +
                "") + " | " + context.getClass().getSimpleName());
    }
}

The activity

String referrer = getSharedPreferences("referral_pref", MODE_PRIVATE).getString("referral", "null");
    Log.e("test", referrer + " was ref");

The logcat

06-01 10:19:27.011 15963-15963 E/TEST: Referrer is: test | test | ReceiverRestrictedContext
06-01 10:19:32.906 15963-15963 E/test: null was ref
Shaun
  • 559
  • 1
  • 3
  • 17

1 Answers1

0

When calling putString(), you have a key named "referrer" and when calling getString(), your key name is "referral".

I'd suggest you create a single static variable named KEY_REFERRER = "referrer" and use it as -

putString(KEY_REFERRER, refferString)

and

getString(KEY_REFERRER, "defaultValue")
Kunal Chawla
  • 1,236
  • 2
  • 11
  • 24