I have activity1, activity2 ,activity3. I want to transfer a string from activity1 to activity3 directly (don't want to open activity3), but want to open activity2 at the same time. Please help me with Java code, I am new to android.
-
So you want to open activity2 and then from activity2 open activity3? With the string in activity3? – Aditya Kurkure May 21 '20 at 08:46
3 Answers
Hi I don't think that'd be directly possible, when starting an activity new Intent()
that's when you pass a string from activity1 to activity2 with new Intent().putExtra("tag","some string")
so you can continue passing the same string from one activity to the other,
or you can opt to store that string in the SharedPreference from activity1 and then access it in any other activity in the application for that use the following code
SharedPreferences pref = getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("StringTag","Some string");
editor.apply();
to Access that string use
SharedPreferences pref =getSharedPreferences("TAG",Context.MODE_PRIVATE);
String myString = pref.getString("StringTag","defaultString");

- 51
- 3
There are many ways of doing it,let me break down two of them.
- First Way: Use Intent's
put.Extra()
method.
As correctly @Lloyd pointed out, you can use Intent put.Extra()
like so:
Intent i = new Intent(CurrentActivity.this,ActivityYouWantToGo.class);
i.putExtra("ObjectName","YourValueHere");
startActivity(i);
and on the other side you simply do:
String yourStringObject= (String) getIntent().getSerializableExtra("ObjectName");
Keep in mind that the second parameter
of putExtra()
has to implement
Serializable , String
class does it by default.
- Second way: Make the
fields
you wantstatic
and get them over with astatic
method.
For instance:
public class MainActivity extends AppCompatActivity {
private static String youStringname = "A Value To Get";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static String getYourString()
{
return youStringname;
}
}
and simply refer to where ever you like like so
String myString = MainActivity.getYourString();
Hope it helps!
Edit: static
usually caches your values

- 1,449
- 1
- 12
- 31
-
Second way suits my condition but my value is not static (have to take value from override onCreate of main activity) – Simar kalsi May 21 '20 at 13:06
-
@Simarkalsi you can try to make it static and initialize it inside `onCreate` – Phill Alexakis May 22 '20 at 19:20
Why would you transfer a value from a activity to another when you don't want to open that activity? Then they value become unused I guess.
Look at intents for transferring a string value from one activity to another.

- 57
- 1
- 2
- 8
-
-
Maybe consider using fragments to avoid having a activity 2. It that case you can pass value through interfaces – Peter Holdensgaard May 21 '20 at 09:03