开发者

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.


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.


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


If they are both in the same application.


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 )
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜