Подтвердить что ты не робот

Класс Android Parcelable с ArrayList

У меня есть проект Android, у которого есть класс. В этом классе есть ArrayList<Choices>. Я получаю некоторый XML, разбираю его, а затем создаю из него объекты, которые я перехожу к другому действию. Я выбираю Parcelable для этого.

Есть ли правильный выбор? Правильно ли я все делаю? Я не знаком с Parcelable. Мой ArrayList имеет другой класс, который я создал в этом классе. Будет ли он правильно передавать этот объект ArrayList на парцеллу, если он не расширяет Parcelable и прочее?

import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.os.ParcelableCompat;

public class Question implements Parcelable{


String id;
String text;
String image;
ArrayList<Choices> CHOICES;


public Question(String id, String text, String image) {
    super();
    this.id = id;
    this.text = text;
    this.image = image;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

@Override
public String toString() {
    return "Question [id=" + id + ", text=" + text + ", image=" + image
            + "]";
}




// Answer Choices class
class Choices {

    boolean isCorrect;
    String choice;

    public Choices(boolean isCorrect, String choice) {
        this.isCorrect = isCorrect;
        this.choice = choice;
    }

    public String getChoice() {
        return choice;
    }

    public boolean getIsCorrect() {
        return isCorrect;
    }

    @Override
    public String toString() {
        return "Choices [isCorrect=" + isCorrect + ", choice=" + choice
                + "]";
    }

}


public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {

    @Override
    public Question createFromParcel(Parcel in) {
        return new Question(in);
    }

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

};

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

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(id);
    dest.writeString(text);
    dest.writeString(image);
    dest.writeList(CHOICES);

}

private Question(Parcel in) {
    this.id = in.readString();
    this.text = in.readString();
    this.image = in.readString();
    this.CHOICES = in.readArrayList(Choices.class.getClassLoader());
}

}

Спасибо за любую помощь!

4b9b3361

Ответ 1

Если вам нужно передать ArrayList между действиями, я бы пошел с реализацией Parcelable, так как другого пути я не думаю. Однако я не думаю, что вам понадобится столько геттеров и сеттеров. Вот ваш класс Question, который реализует Parcelable:

public class Question implements Parcelable {
    public String id;
    public String text;
    public String image;
    public ArrayList<Choice> choices;


    /**
     * Constructs a Question from values
     */
    public Question (String id, String text, String image, ArrayList<Choice> choices) {
        this.id = id;
        this.text = text;
        this.image = image;
        this.choices = choices;
    }

    /**
     * Constructs a Question from a Parcel
     * @param parcel Source Parcel
     */
    public Question (Parcel parcel) {
        this.id = parcel.readString();
        this.text = parcel.readString();
        this.image = parcel.readString();
        this.choices = parcel.readArrayList(null);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    // Required method to write to Parcel
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(text);
        dest.writeString(image);
        dest.writeList(choices);
    }

    // Method to recreate a Question from a Parcel
    public static Creator<Question> CREATOR = new Creator<Question>() {

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }

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

    };
}

Ответ 2

У вас есть это почти, но не совсем, правильно. Класс Question выглядит почти правильно. Единственное, что не сработает, - это парковать множество вариантов.

Есть два способа сделать это:

  • Сделайте выбор возможным. Вам нужно будет добавить все необходимые методы и CREATOR. Поскольку Android знает, как посылить ArrayLists Parcelables, это будет работать.
  • Сделайте парцелляцию массива "Выбор" частью частички вопроса. Чтобы сделать это, вы, вероятно, нажмете размер массива в парцеллу, а затем перейдете через выбор, нажав их значения. С другой стороны, сначала вы должны прочитать счетчик, а затем прочитать значения для каждого выбора, создавая каждый и вставляя его в новый Вопрос.

Ответ 3

Использование:

in.createTypedArrayList(Product.CREATOR)

В конструкторе, который принимает объект Parable в качестве параметра.

В методе writeToParcel используйте dest.writeTypedList(product);