2013-08-29 86 views
0

我有一个应用程序,我试图在活动之间传递类对象。这是我如何做的。如何从Serializable中获取类对象?

类:

public class Player implements Serializable{ 
    public String name; 
    public int score; 
    public static final int serialVersionUID = 12345; 
} 

把类对象的意图额外:

private TextView createNewTextView (String text){ 
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    final TextView newTextView = new TextView(this); 

    newTextView.setLayoutParams(lparams); 
    newTextView.setText(text); 

    Player newPlayer = new Player(); 
    newPlayer.name = text; 
    newPlayer.score = 0; 
    players.add(text); 
    playerScores.add(newPlayer); 
    zacniIgro.putExtra("playerScores", (ArrayList<Player>) playerScores); 
    zacniIgro.putStringArrayListExtra("players", (ArrayList<String>) players); 
    return newTextView; 
} 

获取意图演员在另一个活动:

playersData = getIntent(); 
playerScoresData = getIntent(); 
players = playersData.getStringArrayListExtra("players"); 
playerScores = (ArrayList<Player>) playerScoresData.getSerializableExtra("playerScores"); 

我现在该如何使用这些序列化对象进行操作?我想从playerScores获得某个元素并使用它运行。例如:我想从中获取索引为0的元素,然后使用它的名称和分数进行操作。

+0

不知道这是否是你问:'playerScores.get(0)'将让你'Player'对象。 'playerObj.name'和'playerObj.score'会给你它的名字和分数。 – Vikram

+1

在Android上,您应该使用Parcelable,而不是Serializable –

+0

@ user2558882,但是如何将“playerScores.get(0)”分配给Player对象? – Guy

回答

0
playerScores = (ArrayList<Player>) playerScoresData.getSerializableExtra("playerScores"); 

playerScores得到Player对象:

String nameOfPlayer = playerObj.name; 

要获得得分:

int scoreForPlayer = playerObj.score; 

由于马辛有

Player playerObj = playerScores.get(index); 

玩家的姓名可以通过访问sugges使用Parcelable代替Serializable。序列化非常缓慢。比较:Parcelable vs Serializable

这里更多:Benefit of using Parcelable instead of serializing object