yasser h yasser h - 1 month ago 9
Android Question

Save and increment calls using sharedpreferences

I am trying to save the count of missed calls in one activity and read them in another one.
1st activity:

public class CallReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {

if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
|| intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {

// get the phone number
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

// This code will execute when the call is disconnected
Toast.makeText(context, "missed call number " + incomingNumber, Toast.LENGTH_SHORT).show();

SharedPreferences s = context.getSharedPreferences("s" ,Context.MODE_PRIVATE);
SharedPreferences.Editor e = s.edit();
int count= s.getInt("counter" , 1);



The toast in working and i know the number of the caller but i can't save the count and read it in the 2nd activity:

SharedPreferences s = getSharedPreferences("s" ,Context.MODE_PRIVATE);
int calls = s.getInt("counter" , 0 );

Answer Source

In below line,

    e.putInt("counter", count++); // post increment is error-prone.

could be changed to

    e.putInt("counter", ++count);

Or, just add 1 simply.

    e.putInt("counter", count + 1);