Activity之間傳遞資料

2021-07-27 08:45:16 字數 1670 閱讀 6517

在activity之間傳遞資料時有兩種方式

1、serializable方式:序列化方式,即將乙個物件轉化為可儲存或者是可傳輸的內容,相應的將資料從記憶體卡中讀取出來是反序列化方式

2、parcelable方式:將乙個完整的物件分解成每乙個都可以用intent傳輸的物件。

使用serializable傳遞資料

intent intent = new intent(mainactivity.this, secondactivity.class);

//傳遞boolean型別

intent.putextra("boolean", true);

//傳遞字串型別

intent.putextra("string", "string");

//傳遞整型

intent.putextra("integer", 0);

//有時候需要同時傳遞多個資料,這時我們可以使用乙個bundle將其封裝起來

bundle bundle = new bundle();

bundle.putstring("s", "s");

//傳遞實體類時,必須實現serializable介面

bundle.putserializable("man", new man("jack", 10));

//傳遞字元型

bundle.putchar("char", 'c');

//將bundle放入到intent中

intent.putextras(bundle);

//啟動activity

startactivity(intent);

//獲取資料是也比較簡單,對應型別就行了:

string

data

= getintent().getstringextra("string");

//獲取到bundle物件

bundle extras = getintent().getextras();

//再根據bundle中 型別獲取到對應的資料

使用parceleable傳遞資料

public

class

person

implements

parcelable

//讀取資料:什麼型別對應其相應的型別

protected

person(parcel in)

public

static

final creatorcreator = new creator()

@override

public person newarray(int size)

};@override

public string tostring()

@override

public

intdescribecontents()

//往parcelable中寫入相應的資料

@override

public

void

writetoparcel(parcel dest, int flags)

}讀取方式都是相同的。

在Activity之間傳遞資料

在乙個activity中啟動另乙個activy,取得資料,如 在應用 a 中啟動 通訊錄,選擇目標使用者,返回,以便在a 中使用選擇的通訊錄資料,基本過程如下 intent intent new intent 開啟pictures畫面type設定為image intent.settype image...

不同activity之間資料的傳遞

不同activity之間的資料的傳遞有多種方式,這裡主要記錄兩種方式。第一種是通過bundle來傳遞資料,第二種方法就是直接通過intent來傳遞資料。通過bundle來傳遞資料,首先在主activity中將需要傳遞的資料封裝儲存到bundle中,該部分 如下 bundle bundle new b...

Activity之間傳遞類物件

activity之間通過intent傳遞值,支援基本資料型別和string物件及它們的陣列物件byte byte char char boolean boolean short short int int long long float float double double string stri...