0

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 + " ?";
rodrigobdz
  • 47
  • 3
  • 13

4 Answers4

2

There are 3 ways to do that

  • save this String variable in Shared Preference and in The second Activity get the value .
  • define this variable as Public Static String date and access it from the second Activity like Activity.date directly
  • define this variable as private String date and create getter method for it in the same activity then call it from the other activity
2

The most common interactions:

  1. You can path string by startActivity(new Intent(this, NextActivity.class).putExtra("STRING", yourString));
  2. You can create a singleton and/or class with instance/static var
  3. You can create a variable inside Application class in order to use everywhere.
  4. You can use sharedpreferences to store and retrieve the data.
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

make a static method in some Utils class that would return this string wherever you need it

Lanitka
  • 922
  • 1
  • 10
  • 20
0

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);
Petr Šabata
  • 635
  • 6
  • 7