I Want to save a message on a textView, not just to display it in another activity. For example if the application is closed the next time when will be open I want to see the message which I added.
I have two activities.
Activity one
-> I save the date using SharedPraferences in the variable NAME_RESTAURANT and I sent the date throw method 'getMsg()'Activity two
-> I receive the date and I want to put it into a TextView namedetWelcomeToRestaurant2
The date is represented by a string which I get it from a EditText named etDRestaurantName
in first Activity.
My problem is that in SecondActivity
the date is not displayed.
The activity where I save the date and from where I transmite the date to the Other activity
public class AdminAreaActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
private String NAME_RESTAURANT;
private EditText etDRestaurantName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_area);
etDRestaurantName = findViewById(R.id.etRestaurantName);
final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);
bRestaurantChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!etDRestaurantName.getText().toString().matches("")){
Intent mainIntent = new Intent(AdminAreaActivity.this,MainActivity.class);
saveData();
loadData();
etDRestaurantName.getText().clear();
startActivity(mainIntent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
builder.setMessage("Failed!")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
});
}
public void saveData(){
SharedPreferences sharedPreferences =getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(RESTAURANT_NAME,etDRestaurantName.getText().toString()+"!");
editor.apply();
Toast.makeText(this,"Data saved!",Toast.LENGTH_SHORT);
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
NAME_RESTAURANT = sharedPreferences.getString(RESTAURANT_NAME,"Your Restaurant here!");
}
public String getMsg(){
return NAME_RESTAURANT;
}
}
The activity where I want to put data and where I received it:
public class MainActivity extends AppCompatActivity {
private TextView etWelcomeToRestaurant2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
String messg = "Welcome to,\n";
etWelcomeToRestaurant.setText(messg);
etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
AdminAreaActivity admOBj = new AdminAreaActivity();
etWelcomeToRestaurant2.setText(((AdminAreaActivity)admOBj).getMsg());
}
}