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 EditText et;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize variables
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();
// do stuff
}
// 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();
}