簡體   English   中英

Android-將對象傳遞給另一個活動

[英]Android - Passing an Object To Another Activity

我正在利用我作為對象的跟隨類: http : //pastebin.com/rKmtbDgF

我正在嘗試使用以下方法傳遞它:

Intent booklist = new Intent(getBaseContext(), BookList.class);

Bundle bundle = new Bundle();
bundle.putParcelable("imageManager", (Parcelable) im);                
booklist.putExtras(bundle);
booklist.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(booklist);

我正在嘗試使用以下方式接收它:

ImageManager im  = (ImageManager) getIntent().getExtras().getParcelable("imageManager");

我收到以下錯誤:

java.lang.ClassCastException: com.example.example.ImageManager

嘗試以下帖子。

如何使自定義對象可拆分?

問題是ImageManager不是寓言對象。 這就是強制轉換錯誤。 如果您使用的是imageManager,則應使該類像sais上面的url那樣實現Pracabale。

編輯:

上面應該是做Parceables的正確方法,但是在您的情況下,我真的會說您不應在不同活動之間傳遞ImageManager。 因為您在ImageManager類中使用的上下文將被廢棄。.當然,您會得到一個錯誤。

因此,為什么不改用該類的新實例,而只將Bitmap傳遞給它(在不帶束的情況下轉移了位圖和其他與上下文無關的信息之后)。

轉到此處 ,粘貼您的類結構。它將為您創建可打包的類,然后您可以輕松地將對象傳遞給活動。

最簡單的方法是實現Serializeable ..

import java.io.Serializable;

@SuppressWarnings("serial") 
public class Student implements Serializable {

public Student(int age, String name){
    this.age = age;
    this.name = name;
}

public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public String getName() {
    return this.name;
}
public void setName(String name) {
    this.name = name;
}

private int age;
private String name;

}

將對象從活動A發送到活動B

Student student = new Student (18,"Zar E Ahmer");
Intent i = new Intent(this, B.class);
i.putExtra("studentObject", student);
startActivity(i);

在活動B中獲取對象。

Intent i = getIntent();
Student student = (Student)i.getSerializableExtra("studentObject");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM