Search code examples
androidbroadcastreceiversharedpreferencestransfer

return null when pass virable to BroadcastReceiver


I'm trying to send data on SharedPreferenceson from MainActivity to a BroadcastReceiver.
but that always return null .
I tried very code but all of them returned null.

this is my code on MainActivity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     SharedPreferences shpMobile = getSharedPreferences("text", MODE_PRIVATE);
     final String MobileNumber = (shpMobile.getString("MobileDevice", "0"));
  Intent inte = new Intent();
    inte.setAction("MyBroadcast");

    inte.putExtra("Phone", MobileNumber);

    sendBroadcast(inte);

and this is my BroadcastReceiver class

String phoo1;
@Override
public void onReceive(Context context, Intent intent) {


        //updateWidget();


        Bundle extras = intent.getExtras();
         if (extras != null) {

          String phoo1 = (String) extras.get("Phone");//getting null value

          Toast.makeText(context, phoo1 +"این شماره انتقال دهنده است", 5000).show();
         }

But phoo is null.
Whats wrong?


Solution

  • thanks all. but i cant get value with this solution. and i was searched on net to find another way to get the values. finally ,i find a new sulotion . code is in below: ( i used to Shareperferenced to get values in BroadcastReceiver)

        SharedPreferences prefs = context.getSharedPreferences("text", 
                Context.MODE_PRIVATE);
         final String MobileNumber = (prefs.getString("MobileDevice", null));
    

    this code work for me and reply the our Qustion for @Opiatefuchs request