Ahmed Fahmy Ahmed Fahmy - 28 days ago 12
Android Question

Storing string even if the app is closed

I'm trying to take string from user and use it later when the app is closed..now it works just when the app is in background but i lose the string when i close the app..is there a way to do it like this or i have to use SharedPreference and if i have to use it please explain how because i tried and failed..thanks alot.

this is my code in my MainActivity to the string from the EditText

public class MainActivity extends AppCompatActivity {
private SharedPreferences sharedPreferences;
private static String reminder;
private static AlarmManager am;
private ImageButton btn;
private ImageButton cancel;
private EditText et;
private Intent intent;
private PendingIntent pend;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// initialize variables
btn = (ImageButton) findViewById(R.id.imageButton2);
cancel = (ImageButton) findViewById(R.id.imageButton);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
intent = new Intent(getApplicationContext(), Notifications.class);
pend = getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
// get the user preference
String sel = sp.getString("repeatPref", "1");
final String repeat[] = getResources().getStringArray(R.array.settings_repeat_by_labels);
final int ss = Integer.parseInt(sel);
// action when user presses the "Tweak" button
sharedPreferences = getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
et = (EditText) findViewById(R.id.Name);
reminder = et.getText().toString();
if(reminder == null){
reminder = "TWEAK!";
}

editor.putString("TAG",reminder);
editor.commit();
pend = getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
// if the user didn't type anything
Calendar calendar = Calendar.getInstance();
// notify at different times
if (repeat[ss - 1].equals("15 MINUTES")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES, pend);
}
} else if (repeat[ss - 1].equals("1 HOUR")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 30*1000, pend); //set repeating every 24 hours
}
} else if (repeat[ss - 1].equals("2 HOURS")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR * 2, pend); //set repeating every 24 hours
}
} else if (repeat[ss - 1].equals("4 HOURS")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR * 4, pend); //set repeating every 24 hours
}
}
}

});

// action for "clear alarm" button
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
am.cancel(pend);
pend.cancel();
Toast.makeText(MainActivity.this,"All cleared", Toast.LENGTH_LONG).show();
}

});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

// used to inflate the menu, and respond when users click on our menu item
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, List.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}

// get the user's string
public String getRem() {
reminder = sharedPreferences.getString("TAG", "");
return reminder;
}


the app crashes and gives


"Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference"


at this line

reminder = sharedPreferences.getString("TAG", "");


this is the class where i call the method

public class Notifications extends BroadcastReceiver {
private String rem;

// set notification
@Override
public void onReceive(Context context, Intent intent) {
// object to access MainActivity methods
MainActivity main = new MainActivity();
rem = main.getRem();
}

Answer

Wherever you called the method of getRem(), you can't do that outside the Activity as the SharedPreferences are null.

Like, I assume you made a new MainActivity(), then called getRem() on that, perhaps?

You need to obtain the SharedPreferences again from an available Context, and then you can use getString("TAG", "")

EDIT Borrowed from Shared preferences inside broadcastreceiver

public class Notifications extends BroadcastReceiver {

    private String rem;

    // set notification
    @Override
    public void onReceive(Context context, Intent intent) {
        setRem(context);
    }

    private void setRem(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("MyPREFERENCES",Context.MODE_PRIVATE);
        rem = prefs.getString("TAG", "");
    }

}