2015-11-11 57 views
-1

我有一个自定义类“游戏”,我在活动代码顶部初始化。然后我去另一个活动,通常我通过阵列列表等,但我想移动到传递我的自定义类.....在活动之间传递自定义类实例

我的自定义班'游戏'是一串字符串和arraylist与getter和setter mehtods。

我得到一个

游戏是不是parcelable或序列化对象

错误,当我尝试将其添加到意图。任何想法我可以在这里做什么?

//Init Instance of Game class 
Game newGame = new Game(); 

设置我的听众。它适用于

//Setup onclick listeners 
text.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     Intent i = new Intent(this_Activity.this, next_Activity.class); 
     i.putExtra("players", myList); 
     i.putExtra("newGame", (Parcelable) newGame); 
     startActivityForResult(i, 0); 
    } 
}); 
+0

这一个可能是有用的http:// stacko verx.com/questions/29166753/passing-parcelable-object-between-intents?rq=1 –

回答

3

另外,你的类Game可以实现接口Serializable

public class Game implements Serializable { 
    ... 
} 

你必须改变听者的第一项活动:在next_Activity

text.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     Intent i = new Intent(this_Activity.this, next_Activity.class); 
     i.putExtra("players", myList); 
     i.putExtra("newGame", newGame); 
     startActivityForResult(i, 0); 
    } 
}); 

及更换方法onCreate

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    Game newGame = (Game) getIntent().getExtras().getSerializable("newGame"); 
} 
+0

这是一个梦幻般的,全面而简洁的答案。谢谢亚瑟。 – Fearghal

1

游戏类需要实现Parcelable。

+0

Thx for response。你可以扩展你的答案。 – Fearghal

+0

请参阅https://developer.android.com/reference/android/os/Parcelable.html在那里您可以看到类MyParcelable正在实现Parcelable。 – human123

+0

另请参阅https://stackoverflow.com/questions/5550670/benefit-of-using-parcelable-instead-of-serializing-object来理解为什么Parcelable比序列化更受欢迎 – human123