2016-02-16 249 views
1

我有关于将对象发送到其他活动的问题。我不知道这是怎么做的。所以,我在MainActivity将对象传递给其他活动

final Player player = new Player("Player", 150); 

我对球员单独的类简单的构造

public class Player { 

private String playerName; 
private double playerCash; 

Player(String playerName, double playerCash) 
{ 
    this.playerName = playerName; 
    this.playerCash = playerCash; 
} 

对象的球员,我有第二个活动,在这里我想用Player对象。我使用此代码在MainActivity中制作了一个按钮

mButton = (Button) findViewById(R.id.mButton); 
    mButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(MainActivity.this, SecondActivity.class); 
      intent.putExtra("player", player); 
      startActivity(intent); 
     } 
    }); 

而现在我遇到问题“无法解析方法putExtra”。我究竟做错了什么?我只想要一个Player对象,并希望在多个活动中使用它,但不知道如何。对于任何帮助,非常感谢;)

+0

您无法将意图传递给putExtra中的对象。布尔,int,字符串等是允许的。 – drWisdom

+0

您必须在您的类上实现Serializable并将其作为可序列化移动 –

+2

您的对象需要实现Serializable或Parcelable接口 –

回答

1

以上答案中提到的所有内容都非常清楚地描述了解决方案。 下面是代码:

public class Player implements Parcelable{ 
private String playerName; 
private double playerCash; 

    // Constructor 
    public Player(String playerName, double playerCash){ 
     this.playerName = playerName; 
     this.playerCash = playerCash; 
    } 
    // Implement Getter and setter methods 


    // Parcelling part 
    public Player(Parcel in){ 
     this.playerName = in.readString(); 
     this.playerCash = in.readDouble(); 
    } 

    @Оverride 
    public int describeContents(){ 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(playerName); 
     dest.writeDouble(playerCash); 
    } 
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { 
     public Player createFromParcel(Parcel in) { 
      return new Player(in); 
     } 

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

让一个Serializable类

import java.io.Serializable; 

@SuppressWarnings( “串行”) 公共类MyPlayer实现Serializable {

私人字符串playerName; 私人双人球员现金;

public MyPlayer(String playerName, double playerCash) { 
    this.playerName = playerName; 
    this.playerCash = playerCash; 
} 

public String getPlayerName() { 
    return playerName; 
} 

public void setPlayerName(String playerName) { 
    this.playerName = playerName; 
} 

public double getPlayerCash() { 
    return this.playerCash; 
} 

public void setPlayerCash(double playerCash) { 
    this.playerCash = playerCash; 
} 

}

然后在点击按钮把

mButton = (Button) findViewById(R.id.mButton); 
mButton.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     MyPlayer myPlayer = new MyPlayer(playerName,playerCash); 
     Intent i = new Intent(MainActivity.this, SecondActivity.class); 
     i.putExtra("key", myPlayer); 
     startActivity(i); 
    } 
}); 

如要传递的数据使用(在第二个活动)

Intent i = getIntent(); 

MyPlayer myPlayer =(MyPlayer)我。 getSerializableExtra( “钥匙”);

相关问题