-3

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.

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46

3 Answers3

3

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

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 want static and get them over with a static 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

Phill Alexakis
  • 1,449
  • 1
  • 12
  • 31
0

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.