I need to parse a single text from my MainActivity.java to all other activities in my app.
Is it possible to do so?

- 995
- 1
- 10
- 21

- 31
- 4
-
1pass that string in the intent and extract the same in the other activity, or use shared preference to access data across the activities – Sri Madhan Dec 30 '17 at 08:17
-
Use Shared Preference. [Shared Preference Example](https://stackoverflow.com/questions/23024831/android-shared-preferences-example) – Rajat Mehra Dec 30 '17 at 08:33
-
Don't you mean pass instead of parse? – Ridcully Dec 30 '17 at 09:06
4 Answers
Just store the text as string in shared preferences
and then get the string in other activities.. or you can also use broadcast receiver
in all other activities. But first all the activities should call the receiver
first then the MainActivity can send the text.
In MainActivity,
this.getSharedPreferences("MyPrefName", Context.MODE_PRIVATE).edit().putString("parsetext","yourtext").apply();
and in the other activities..
this.getSharedPreferences("MyPrefName", Context.MODE_PRIVATE).getString("parsetext","");

- 10,997
- 7
- 33
- 52
-
BroadcastReceiver is not for inter-activities comunication for obvious reason – Selvin Dec 30 '17 at 08:26
-
yes it aint .. . and @ManigandanS i have given the code just store the result in a string variable. – Santanu Sur Dec 30 '17 at 08:33
-
Better way is to pass data between activities. Code:
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("parsetext", "your text here");
startActivity(intent);
Access that intent on next activity:
String s = getIntent().getStringExtra("parsetext");

- 879
- 2
- 13
- 34
Your question sounds you need global access of some data in your all Activites, whenever something is needed to be accessed temporarily that is, for the time until application is active you can use your Application class, which is globally accessible through getApplicationContext()
in all Activites.
For reference see this answer: https://stackoverflow.com/a/1945297/4878972
But if the data you need to access in all the Activites needs to get saved permanently then you can go for Shared Preference approach.

- 1,673
- 12
- 19
You can have a public static final String in your MainActivity and access that String from another activity. As in:
In MainActivity.java
public static final String MY_STRING = "my string";
In other places where you need to access the variable, you can access is as:
String string = MainActivity.MY_STRING;

- 1,086
- 7
- 8