簡體   English   中英

將自定義對象數組傳遞給android中的另一個Activity

[英]Pass array of custom objects to another Activity in android

我是android編程的新手,我正在嘗試將自定義對象的數組發送到其他活動。 在第一個活動中,我有一個創建意圖並向其中添加對象數組的函數:

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    nextScreen.putExtra("array", tasks);
    startActivity(nextScreen);
}

但是,我不確定如何在下一個屏幕上獲取該數據。

即使“任務”是自定義對象的數組,有沒有辦法在代碼中為下一個活動獲取該數組?

您是否曾與Gson嘗試過?

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    String arrayAsString = new Gson().toJson(tasks);
    nextScreen.putExtra("array", arrayAsString);
    startActivity(nextScreen);
}

在第二個活動中,將多余的數據解析回List<T>

public void parseBack(){
    String arrayAsString = getIntent().getExtras().getString("array");
    List<YourType> list = Arrays.asList(new Gson().fromJson(arrayAsString, YourType[].class));
}

讓你的自定義對象實現Parcelable ,為了利用putParcelableArrayListExtraIntent類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM