如何在Android上將對象從一項活動傳遞到另外一項活動

我正在嘗試從一個Activity發送個人客戶類的對象並將其顯示在另外一個Activityhtml

客戶類的代碼: java

public class Customer {

    private String firstName, lastName, Address;
    int Age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        Age = age;
        Address = address;
    }

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + Age + " Address : " + Address;

        return data;
    }
}

我想將其對象從一個Activity發送到另外一個,而後在另外一個Activity上顯示數據。 android

我該如何實現? 數據庫


#1樓

  • 使用全局靜態變量不是良好的軟件工程實踐。
  • 將對象的字段轉換爲原始數據類型可能會很麻煩
  • 使用serializable是能夠的,但在Android平臺上性能不高
  • Parcelable是專爲Android設計的,您應該使用它。 這是一個簡單的示例: 在Android活動之間傳遞自定義對象

您可使用此站點爲您的班級生成Parcelable代碼。 網絡


#2樓

我製做了一個包含臨時對象的單例助手類。 數據結構

public class IntentHelper {

    private static IntentHelper _instance;
    private Hashtable<String, Object> _hash;

    private IntentHelper() {
        _hash = new Hashtable<String, Object>();
    }

    private static IntentHelper getInstance() {
        if(_instance==null) {
            _instance = new IntentHelper();
        }
        return _instance;
    }

    public static void addObjectForKey(Object object, String key) {
        getInstance()._hash.put(key, object);
    }

    public static Object getObjectForKey(String key) {
        IntentHelper helper = getInstance();
        Object data = helper._hash.get(key);
        helper._hash.remove(key);
        helper = null;
        return data;
    }
}

不要將對象放在Intent中,而要使用IntentHelper: 性能

IntentHelper.addObjectForKey(obj, "key");

在新的Activity中,您能夠獲取該對象: this

Object obj = (Object) IntentHelper.getObjectForKey("key");

請記住,一旦加載,該對象將被刪除以免沒必要要的引用。 spa


#3樓

  1. 我知道static很很差,可是彷佛咱們不得不在這裏使用它。 parceables / seriazables的問題在於兩個活動具備相同對象的重複實例=浪費內存和CPU。 設計

    public class IntentMailBox { static Queue<Object> content = new LinkedList<Object>(); }

通話活動

IntentMailBox.content.add(level);
Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
startActivity(intent);

被調用的活動(請注意,當系統銷燬並從新建立活動時, onCreate()onResume()可能會被屢次調用)

if (IntentMailBox.content.size()>0)
    level = (Level) IntentMailBox.content.poll();
else
    // Here you reload what you have saved in onPause()
  1. 另外一種方法是聲明要在該類中傳遞的類的靜態字段。 它僅用於此目的。 不要忘記在onCreate中它能夠爲null,由於您的應用程序包已由系統從內存中卸載並在之後從新加載。

  2. 請記住,您仍然須要處理活動生命週期,所以您可能但願將全部數據直接寫到共享的首選項,這樣就很難處理複雜的數據結構。


#4樓

您能夠經過兩種方法訪問其餘類或Activity中的變量或對象。

A.數據庫

B.共同的偏好。

C.對象序列化。

D.能夠保存通用數據的類能夠稱爲通用實用程序。 這取決於你。

E.經過意圖和可打包接口傳遞數據。

這取決於您的項目需求。

A. 數據庫

SQLite是嵌入到Android中的開源數據庫。 SQLite支持標準的關係數據庫功能,例如SQL語法,事務和準備好的語句。

講解

B. 共同的偏好

假設您要存儲用戶名。 所以,如今有兩件事,一個用戶名, value。

如何儲存

// Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

 //Now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();

 //Put your value
 editor.putString("userName", "stackoverlow");

 //Commits your edits
 editor.commit();

使用putString(),putBoolean(),putInt(),putFloat()和putLong()能夠保存所需的dtatype。

如何取得

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

C. 對象序列化

若是咱們要保存對象狀態以經過網絡發送它,或者您也能夠將其用於您的目的,則使用對象序列化。

使用Java bean並將其存儲爲他的領域之一,併爲此使用getter和setter。

JavaBean是具備屬性的Java類。 將屬性視爲私有實例變量。 因爲它們是私有的,所以能夠從類外部訪問它們的惟一方法是經過類中的方法。 更改屬性值的方法稱爲setter方法,而檢索屬性值的方法稱爲getter方法。

public class VariableStorage implements Serializable  {

    private String inString;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }
}

使用如下命令在您的郵件方法中設置變量

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

而後使用對象序列化對該對象進行序列化,並在其餘類中對該對象進行反序列化。

在序列化中,對象能夠表示爲字節序列,其中包括對象的數據以及有關對象的類型和對象中存儲的數據類型的信息。

將序列化對象寫入文件後,能夠從文件中讀取並反序列化。 即,表示對象及其數據的類型信息和字節可用於在內存中從新建立對象。

若是您要使用此教程,請參考:

D. 公用事業

您能夠本身建立一個類,其中能夠包含項目中常常須要的通用數據。

樣品

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E. 經過意圖傳遞數據

請參閱Android – Parcel數據教程, 以使用Parcelable類在Activity之間進行傳遞,以瞭解此傳遞數據的選項。


#5樓

我正在使用parcelable將數據從一項活動發送到另外一項活動。 這是個人代碼,在個人項目中工做正常。

public class Channel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String uniqueID;
    private String name;
    private String logo;
    private String thumb;


    /**
     * @return The cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *     The cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return The uniqueID
     */
    public String getUniqueID() {
        return uniqueID;
    }

    /**
     * @param uniqueID
     *     The uniqueID to set
     */
    public void setUniqueID(String uniqueID) {
        this.uniqueID = uniqueID;
    }

    /**
     * @return The name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            The name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the logo
     */
    public String getLogo() {
        return logo;
    }

    /**
     * @param logo
     *     The logo to set
     */
    public void setLogo(String logo) {
        this.logo = logo;
    }

    /**
     * @return the thumb
     */
    public String getThumb() {
        return thumb;
    }

    /**
     * @param thumb
     *     The thumb to set
     */
    public void setThumb(String thumb) {
        this.thumb = thumb;
    }


    public Channel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
        public Channel createFromParcel(Parcel in) {
            return new Channel(in);
        }

        public Channel[] newArray(int size) {

            return new Channel[size];
        }
    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[5];
        in.readStringArray(result);

        this.cid = result[0];
        this.uniqueID = result[1];
        this.name = result[2];
        this.logo = result[3];
        this.thumb = result[4];
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeStringArray(new String[] { this.cid, this.uniqueID,
                this.name, this.logo, this.thumb});
    }
}

在activityA中像這樣使用它:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels);
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras(bundle);
startActivity(intent);

在ActivityB中像這樣使用它來獲取數據:

Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");
相關文章
相關標籤/搜索