向Activity传递实现Parcelable接口的ArrayList

34

我已经搜索了一些主题,但没有找到解决我的问题的方法。

public class Series implements Parcelable {
private String name;
private int numOfSeason;
private int numOfEpisode;

/** Constructors and Getters/Setters have been removed to make reading easier **/

public Series(Parcel in) {
    String[] data = new String[3];
    in.readStringArray(data);
    this.name = data[0];
    this.numOfSeason = Integer.parseInt(data[1]);
    this.numOfEpisode = Integer.parseInt(data[2]);
}


@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeStringArray(new String[] { this.name,
            String.valueOf(this.numOfSeason),
            String.valueOf(this.numOfEpisode) });

}

private void readFromParcel(Parcel in) {
    name = in.readString();
    numOfSeason = in.readInt();
    numOfEpisode = in.readInt();
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    @Override
    public Series createFromParcel(Parcel in) {
        return new Series(in);
    }

    @Override
    public Series[] newArray(int size) {
        return new Series[size];
    }
};

}

在我的MainActivity中,我有一个ArrayList。为了使列表可以动态编辑,我需要将它传递到另一个活动中进行编辑。

ArrayList<Series> listOfSeries = new ArrayList<Series>();

    public void openAddActivity() {
    Intent intent = new Intent(this, AddActivity.class);
    intent.putParcelableArrayListExtra(
            "com.example.episodetracker.listofseries",
            (ArrayList<? extends Parcelable>) listOfSeries);
    startActivity(intent);
}

我需要转换列表,否则Eclipse会给出以下错误信息。 Intent中的putParcelableArrayListExtra(String, ArrayList)方法不适用于参数(String, List) 这样做是否正确?
    ArrayList<Series> list = savedInstanceState
            .getParcelableArrayList("com.example.episodetracker.listofseries");

这是我尝试在另一个活动中读取数据的方式。
它会在上面一行崩溃,即getParcelableArrayList部分。

1/ 我不明白你的代码哪里出了问题。 2/ 你没有把列表保存在某个地方吗?因此,最好是在数据库上工作,而不是在从一个活动传递到另一个活动的数组上工作。 - njzk2
Parcelables 可以说是魔鬼... 你尝试过将其改为可序列化对象吗? - snowCrabs
1
我一直以为Parcelable是更好的选择,因为Serializable速度较慢? - Adrian Jandl
Parcelable使得复杂类更容易处理。就速度而言,我们讨论的是多少数据项? - snowCrabs
一个包含大约10个条目的ArrayList,每个条目都有3个成员变量。 - Adrian Jandl
6个回答

42
  • The problem is in writing out to the parcel and reading in from the parcel ...

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(numOfSeason);
        dest.writeInt(numOfEpisode);
    }
    
    private void readFromParcel(Parcel in) {
        name = in.readString();
        numOfSeason = in.readInt();
        numOfEpisode = in.readInt();
    }
    
  • What you write out has to match what you read in...

    @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    Intent i = new Intent(this,SecondActivity.class);
    
    ArrayList<testparcel> testing = new ArrayList<testparcel>();
    
    i.putParcelableArrayListExtra("extraextra", testing);
    startActivity(i);
    }
    
        /**********************************************/
    
    
    public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        ArrayList<testparcel> testing = this.getIntent().getParcelableArrayListExtra("extraextra");
     }
    }
    
  • The above code is having onCreate() from two different activities. The first one launches the second one; and it works fine I was able to pull the parcelable without issue.


已经修改了代码,但是NullPointerException仍然存在。虽然在这部分没有做任何更改。ArrayList<Series> list = savedInstanceState .getParcelableArrayList("com.example.episodetracker.listofseries"); - Adrian Jandl
在包中的名称并不重要,您可以将其称为“ MyArray”作为键,它应该可以工作。它在哪一行崩溃了? - snowCrabs
在我“加载”新活动的那一行崩溃了。具体来说,就是这一行:ArrayList<Series> list = savedInstanceState .getParcelableArrayList("com.example.episodetracker.listofseries"); - Adrian Jandl
1
你必须从意图中调用,而不是从savedInstanceState中调用。 - snowCrabs
我困在一个小时的死循环中... 除了顺序之外一切都完美... - me_

3

我曾经使用过从Bundle对象中提取putParcelableArrayList(<? extends Parcelable>)。并没有直接从Intent对象中提取(我并不知道它们之间的区别)。但是我通常会按照以下方式使用:

ArrayList<ParcelableRow> resultSet = new ArrayList<ParcelableRow>();
resultSet = loadData();

Bundle data = new Bundle();
data.putParcelableArrayList("search.resultSet", resultSet);
yourIntent.putExtra("result.content", data);
startActivity(yourIntent);

在您的新活动中,您可以像这样填充最近插入的数据到 Bundle 对象中:

Bundle data = this.getIntent().getBundleExtra("result.content");
ArrayList<ParcelableRow> result = data.getParcelableArrayList("search.resultset");

请记住,您的ArrayList<>必须只包含可捆绑的对象。为了确保已传递数据,您可以检查接收到的数据是否为空,以避免问题。


3

intent.putParcelableArrayListExtra("com.example.episodetracker.listofseries", (ArrayList<? extends Parcelable>) listOfSeries);这样做是正确的吗? 如果我不进行强制转换,就会出现以下错误: Intent 中的 putParcelableArrayListExtra(String, ArrayList<? extends Parcelable>) 方法不适用于参数 (String, List<Series>) - Adrian Jandl
12
请将您的listOfSeries声明为ArrayList,而不是List - Ovidiu Latcu
1
好的,编译器现在很开心了。 但是,一旦我尝试读取数据,程序仍然会崩溃。我已经在原帖中更新了一个logcat片段。 - Adrian Jandl

0

你可以传递 Parcelable ArrayList

发送方 Activity ->

startActivity(Intent(this, SenderActivity::class.java).apply { putExtra("getList",list)})

接收方 Activity ->

private lateinit var list: ArrayList<List>

list = this.intent.extras?.getParcelableArrayList("getList")!!

这样你就可以得到所有的 ArrayList。


0
也许这可以帮助到其他人。我的问题是我使用了write和readValue,但它们应该匹配类型,如writeInt、readInt、writeString、readString等等。

0

我是这样做的:

var intent = Intent(this@McqActivity,ResultActivity::class.java)
intent.putParcelableArrayListExtra("keyResults", ArrayList(resultList)) 
// resultList  is of type mutableListOf<ResultBO>()  
 startActivity(intent)

对于使类可 Parcelable 化,我只需执行两个操作。首先,在我的数据类上方使用@Parcelize注释,其次是继承它并使用Parcelable,如下所示...

import kotlinx.android.parcel.Parcelize
import android.os.Parcelable

@Parcelize // Include Annotion 
data class ResultBO(val questionBO: QuestionBO) : Parcelable {
    constructor() : this(QuestionBO())
}

在接收端

if (intent != null) {
     var results = intent.getParcelableArrayListExtra<Parcelable>("keyResults")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接