如何获取数组中自定义对象的 Intent?

How can I get Intent of my custom object in array?

这是里面的内容Player.class

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Created by pietsteph on 15/09/17.
 */

public class Player implements Parcelable{
String name;
int score;


protected Player(Parcel in) {
    name = in.readString();
    score = in.readInt();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeInt(score);
}

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

public static final Creator<Player> CREATOR = new Creator<Player>() {
    @Override
    public Player createFromParcel(Parcel in) {
        return new Player(in);
    }

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getScore() {
    return score;
}

public void setScore(int score) {
    this.score = score;
}

public Player(String name) {
    this.name = name;
    this.score = 0;
}

}

在 MainActivity.class 中,我将自定义对象制作为大小为 2(2 个玩家)的数组,并将其放入意图中。

Player players[] = new Player[2];
players[0] = new Player(name1);
players[1] = new Player(name2);

Intent intent = new Intent(getApplicationContext(), TurnActivity.class);
intent.putExtra(PLAYER_KEY, players);
startActivity(intent);

想要在 TurnActivity.class 中获得我的意图,尝试了 getParcelableExtra。

Intent intent = getIntent();
Player players[] = intent.getParcelableExtra(MainActivity.PLAYER_KEY);

但是它给了我一个错误

Error:(28, 59) error: incompatible types: inferred type does not conform to upper bound(s)inferred: INT#1
upper bound(s): Player[],Parcelable
where INT#1 is an intersection type:
INT#1 extends Player[],Parcelable

甚至尝试了 getParcelableArrayExtra 并给了我一条红线,上面写着不兼容的类型。

实施

Parcalable

的接口

Player

class 我用了

Android Parcelable code generator plugin

来完成这个任务。 那么您就可以将自定义对象数组保存在 intents 中。

这是 Java 8 的问题。您可能需要这样做:

Intent intent = getIntent();
Parcelable parcelable[] = intent.getParcelableArrayExtra(MainActivity.PLAYER_KEY);

现在,当您使用它时,您需要将其转换为正确的类型。像这样:

Player player = (Player)parcelable[0];

我曾经做过这样的事情

public void moveToNext(ArrayList images){

    Intent mainIntent = new Intent(SplashScreen.this,MainActivity.class);

//add data to parcalable

    mainIntent.putParcelableArrayListExtra("data",images);


    startActivity(mainIntent);
    finish();
}

//获取数据时

ArrayList v = getIntent().getParcelableArrayListExtra("data");