0

我有一个名为 Boy 的类,它有一个 type 的实例变量ArrayList Question>。另一方面,问题有 5 个字符串类型的实例变量。当我打开包装时,Arraylist Question>我尝试读取问题的字符串值之一,而不是我得到的实际值com.example.test.Question@418a39e0或类似的文本,具体取决于我选择的问题。

请问为什么会这样?

这是班男孩

public class Boy implements Parcelable{
ArrayList<Question> questionList;

public Boy(){
    questionList = new ArrayList<Question>();
    Question ques1 = new Question();
    Question ques2 = new Question();
    questionList.add(ques1);
    questionList.add(ques2);
}

@SuppressWarnings("unchecked")
public Boy(Parcel in) {
    questionList = in.readArrayList(Question.class.getClassLoader());
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeList(questionList);
}

public static final Parcelable.Creator<Boy> CREATOR
= new Parcelable.Creator<Boy>() {
    public Boy createFromParcel(Parcel in) {
        return new Boy(in);
    }

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

这是课堂问题

 public class Question implements Parcelable{
public String ques = "how do you create a parcelable?";

public Question(){

}

public Question(Parcel in) {
    ques = in.readString();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(ques);
}

public static final Parcelable.Creator<Question> CREATOR
= new Parcelable.Creator<Question>() {
    public Question createFromParcel(Parcel in) {
        return new Question(in);
    }

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

此代码显示控制第二个活动的类。我正在尝试打开 arrayList 并阅读其问题的内容之一,而不是我得到的实际文本com.example.test.Question@418a39e0

 public class SecondActivity extends Activity{

TextView tv1;
TextView tv2;
String ques1;
String ques2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second_layout);

    Boy b = (Boy)getIntent().getExtras().getParcelable("marcus");
    ques1 = b.questionList.get(0).toString();
    ques2 = b.questionList.get(1).toString();

    tv1 = (TextView)findViewById(R.id.textView1);
    tv2= (TextView)findViewById(R.id.textView2);
    tv1.setText(ques1);
    tv2.setText(ques2);
}
 }
4

1 回答 1

0

您必须在 Question 类中覆盖 toString() 以打印出您需要的内容。

于 2013-06-06T19:28:59.047 回答