Using static methods in Android with getApplicationContext()?

android, sms

Solution

You can make these methods static by adding a Context parameter

public static void reply(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    final String message = settings.getString("message", "@string/pd_message");

    send(context, Receiver.number, message);
}

public void send(Context context, String number, String message) {
    PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, Main.class), 0);
    SmsManager sm = SmsManager.getDefault();
    if (Receiver.number != "") {
        sm.sendTextMessage(number, null, message, pi, null);
    }
}

Problem

I am working on an app called Drive Mode which will allow the user to enter a custom message in the settings and have this message auto-replied to any incoming text. (Along with other features of course) My problem is trying to reference a static string and using getApplicationContext(); I am grabbing the text from an EditTextPreference and am trying to access this string in multiple activities. FIXED: This problem is now fixed and I have edited the entire post to better help others who possibly have this same problem. Thank you for all the help. ``` public class Main extends Activity implements OnSharedPreferenceChangeListener { ... public static String reply = ""; ... public void loadPreferences() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); settings.registerOnSharedPreferenceChangeListener(Main.this); if (settings.getBoolean("cbReply", true)) { reply = settings.getString("tbMessage", "@string/pd_message"); ... } else { ... } ```

Original source

Related problems