I have created a string in an activity and I want to make it available else in another activity. How can I do that?
This is the string:
String date = dayOfMonth + "/" + month + "/" + year + " ?";
I have created a string in an activity and I want to make it available else in another activity. How can I do that?
This is the string:
String date = dayOfMonth + "/" + month + "/" + year + " ?";
There are 3 ways to do that
The most common interactions:
startActivity(new Intent(this, NextActivity.class).putExtra("STRING", yourString));
make a static method in some Utils class that would return this string wherever you need it
Use an intent to pass it to the other activity (https://developer.android.com/guide/components/intents-filters.html) or store it to shared preferences (https://developer.android.com/training/basics/data-storage/shared-preferences.html).
Intent works like this:
// Write
Intent intent = new Intent(context, Activity.class);
intent.putExtra("EXTRA_PARAMETER", parameterValue);
startActivity(intent);
//Read
String parameter = getIntent().getStringExtra("EXTRA_PARAMETER");
Shared preferences work like this:
// Write
SharedPreferences sharedPref =
getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
// Read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);