How to store string / integer value in Broadcast receiver.?

638 views Asked by At

I have one receiver which extend Broadcast Receiver.I am passing string value from main activity. when activity create it pass the value to receiver.I can receive that string value. But my problem is, I can not save that string values.

i have tried shared preference with context in Broadcast Receiver but it is not working.

My Receiver code is Here.

public void onReceive(Context context, Intent intent)
{


  if(intent.getAction().equals("my.action.string")){
         state = intent.getExtras().getString("value");

         Toast.makeText(context, "this is state : " + state, Toast.LENGTH_SHORT).show();

        SharedPreferences prefs = context.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
                Editor editor = prefs.edit();
                editor.putString("state_lock", state);
                editor.commit();

            p = prefs.getString("state_type", state);
      Toast.makeText(context, "the state type is : "+ p, Toast.LENGTH_SHORT).show();
}

With this code i can get only data but can not store them.

anyone can help me. How can I store data in Broadcast Receiver.?

thank you in advance.

2

There are 2 answers

3
Chandrakanth On

You are saving data using "stae_lock" key value and getting data using "state_type" To get the value you stored previously use the same key like

 p = prefs.getString("state_lock", state);
1
balu b On
p = prefs.getString("state_type", state);

instead of use following to get data

p = prefs.getString("state_lock", state);