sivaraj
sivaraj

Reputation: 1867

how to pass an array from one activity to another activity in android

I want to pass an array from one Activity to another Activity,for example I need to pass an array from image_view Activity to Blackimage Activity.Please give solution to this problem in Android.

Upvotes: 0

Views: 2035

Answers (5)

codeScriber
codeScriber

Reputation: 4612

Passing it through the activity will be the best performance choice, as if you use preferenes or the Intent to pass on the array you will have to loop over the array to persist it and recover it from the Intent or Preferences.

Using the Application will allow you to pass on the array, but doing so, just like with a singletone will force you to handle it instance being destroyed as if you wont do it it wont be GCed even after the two activities died since the application will still keep a reference to it.

Upvotes: 0

TxAg
TxAg

Reputation: 1485

In addition to the singleton class, you might want to look at using the Android SharedPreferences to save/get any data to either save your settings or prevent loss of data if interrupted.

Also adding android:configChanges="keyboardHidden|orientation"> into the AndroidManifest will prevent your app from losing data if you rotate screens/slide open keyboard.

SharedPref Example

 String m_myData[];
 Boolean m_myBoolData[];

public static void saveSettings()
{
    SharedPreferences.Editor editor = m_SharedPreferences.edit();
    for(int ix = 0; ix < m_myData[].length; ix++
    {
       editor.putString("myKey" + ix, m_myData[ix]);
       editor.putBoolean("myKey" + ix, m_myBoolData[ix])
    }
}

public static void getSettings()
{

    for(int ix = 0; ix < m_myData[].length; ix++
    {
      m_myData[ix] = m_SharedPreferences.getString("myKey" + ix, false);
      m_myBoolData[ix] = m_SharedPreferences.getBoolean("myKey" + ix, false )
    }
}

Upvotes: 0

Yoni Samlan
Yoni Samlan

Reputation: 38065

Using a Singleton is probably a bad idea here, especially given Android's kill-happy lifecycle and the high likelihood of leaking Context if you do it wrong. Android has a very simple and powerful built-in message-passing capability on Intents - use it! You should pass the array as an Extra on the Intent, either using the built-in putExtra methods that take Arrays of various Java builtins, or by making sure your array is made of Serializable objects and passing it to the Intent's putExtra method that takes any serializable object. Then you can simply get the extra out of the Intent in the second Activity's onCreate(), no messy singletons necessary.

Upvotes: 5

Pontus Gagge
Pontus Gagge

Reputation: 17258

If they are both in the same application.

Upvotes: 0

fredley
fredley

Reputation: 33901

Read up on making a singleton class, then you can call singleton.setArray(myArray) in one Activity, and singleton.getArray() in the next.

Upvotes: 3

Related Questions