-2

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

Swati Garg
  • 801
  • 1
  • 9
  • 21

4 Answers4

1

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","");

Santanu Sur
  • 8,836
  • 7
  • 24
  • 43
0

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");
salih kallai
  • 877
  • 2
  • 11
  • 32
0

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.

Aseem Sharma
  • 1,205
  • 10
  • 18
0

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;
Shivam
  • 746
  • 5
  • 7