我使用parcelable成功传递了对象的arraylist。但是,当我试图将一个对象从一个活动传递到另一个活动时,它无法工作。
在第一个Activity(ShowActivity)中,我有一个gridView,对于onclick,我想将一个对象发送到另一个活动,并显示1个对象的值的结果:
ShowActivity ::
gridView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id)
{
aStudent = students.get(position);
Toast.makeText(ShowActivity.this, String.valueOf(aStudent.getstudentdID()), 2000).show();
/*Intent myIntent = new Intent(ShowActivity.this,ViewStudentInfoActivity.class);
myIntent.putExtra("studentObj", aStudent);
//myIntent.putExtra("studentObj", aStudent.getstudentName());
startActivity(myIntent);*/
Bundle b = new Bundle();
b.putParcelable("studentObj", aStudent);
Intent myIntent2 = new Intent(ShowActivity.this,ViewStudentInfoActivity.class);
startActivity(myIntent2.putExtras(b));
}
});
在ViewStudentInfoActivity ::
的onCreate()中@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewstudent_info);
getPassedVal();
}
private void getPassedVal()
{
Intent intent = new Intent();
/* if(intent!=null)
{
Student aaStudent = (Student) intent.getParcelableExtra("studentObj");
Log.d("vv", aaStudent.getstudentName());
} */
Bundle b = getIntent().getExtras();
if(b != null) {
Student aaStudent = (Student)(b.getParcelable("studentObj"));
String str = aaStudent.getstudentName().toString();
}
}
虽然吐司正在显示结果,但这意味着对象没问题。但是不能从第二次活动中收回它吗?有点奇怪。我做错了吗?
答案 0 :(得分:1)
看看以下几行:
b.putParcelable("studentObj", aStudent);
Student aaStudent = (Student)(b.getParcelable("aStudent"));
您使用不同的密钥。 “studentObj”vs“aStudent”。
答案 1 :(得分:0)
尝试使用以下代码:
b.putExtra("studentObj", aStudent); // instead of b.putParcelable
并获得了:
Student aaStudent = b.getParcelable("studentObj");
如果这对您没有帮助,请发布Student
课程