5

I am having two activities in my application. I want to pass tha array of String from one activity to another.. How to pass this values from activity to activity?

Thiru
  • 2,374
  • 7
  • 21
  • 29

6 Answers6

16

You can consider using Intent.getStringArrayExtra

In the first activity:

Intent intent = new Intent(context, NewActivity.class);
intent.putExtra("string-array", stringArray);
context.startActivity(intent);

and in the second one:

Intent intent = getIntent();
String [] stringArray = intent.getStringArrayExtra("string-array");
Amit W
  • 3
  • 2
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
3

Here's some reading: http://www.vogella.de/articles/AndroidIntent/article.html#overview_accessdata go to section 2.1.

Also, How to pass ArrayList using putStringArrayListExtra() should explain something similar.

Community
  • 1
  • 1
AJcodez
  • 31,780
  • 20
  • 84
  • 118
2

In Activity One, write this code to create an array and pass it to another activity:

String[] array1={"asd","fgh","dcf","dg","ere","dsf"};
Intent i=new Intent(MainActivity.this,Main2Activity.class);
i.putExtra("key",array1);
startActivity(i);

In Second Activity, write this to retrieve your array

String[] array = getIntent().getStringArrayExtra("key"); 
Jim Hewitt
  • 1,726
  • 4
  • 24
  • 26
2

just serialize it and set it in the extras of the intent (of activity) you wanna open.
You will receive it in the onCreate() of that activity.
Convert it to array again.

akkilis
  • 1,904
  • 14
  • 21
  • 1
    consider using @kgiannakakis 's sample. Its more straight forward than what I told. I got Intent.getStringArrayExtra skipped from my mind. – akkilis Jan 17 '12 at 10:29
1
Intent myIntent = new Intent(getApplicationcontext, NewActivity.class);
intent.putExtra("mStringArray", mystringArray);
startActivity(myIntent);

In the New activity in onCreate event

String[] mystringArray = getIntent().getStringArrayExtra("mStringArray");

If you want to send more data with different data types you should use BUNDLE.

Kishan Viramgama
  • 893
  • 1
  • 11
  • 23
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
0

Its very simple, make that variable static & make one public static method in that class like

public static getArray() 
{ 
        return array; 
} 

Now access this method from another activity, where you want to access it.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • 4
    I wud say its not a good coding practice to have your data variables static and giving the access to modify them from anywhere the app. Best way is to pass it through the bundles in the intent. Try to do it as in the ans from @kgiannakakis, as its not about the ease but about the stability and robustness in the code makes you a good programmer. – akkilis Jan 17 '12 at 11:21