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

Передача ArrayList объектов через намерение - Java (Android)

Я пытаюсь передать объект ArrayList через намерение, но не могу заставить его работать. Вот что я имею:

public class QuestionView extends Activity {

    //variables and other methods...

    public void endQuiz() {
        Intent intent = new Intent(QuestionView.this, Results.class);
        intent.putExtra("correctAnswers", correctAnswers);
        intent.putExtra("wrongAnswers", wrongAnswers);
        intent.putParcelableArrayListExtra("queries", queries);
        startActivity(intent);
    }
}

Здесь принимаются намерения:

public class Results extends Activity {

    int cAnswers;
    int wAnswers;
    ArrayList<Question> qs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.resultsmain);

        cAnswers = getIntent().getIntExtra("correctAnswers", -1);
        wAnswers = getIntent().getIntExtra("wrongAnswers", -1);

        qs = getIntent().getParcelableArrayListExtra("queries");

                    //more code...
    }
}

Получают два ints, correctAnswer и wrongAnswers, и я могу их использовать. ArrrayList не проходит. Нет ошибок в методе endQuiz(), но "qs = getIntent(). GetParcelableArrayListExtra (" запросы "); выдает ошибку и говорит" Связанное несоответствие".

Любая помощь по этому поводу оценивается!

Класс вопросов:

public class Question {
    String a1;
    String a2;
    String a3;
    String a4;
    int correctAnswer;
    String query;
    int selectedAnswer;
    boolean correctness;

    public Question() {
    }

    public Question(String a1, String a2, String a3, String a4, int correctAnswer, String query, int selectedAnswer, boolean correctness) {
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
        this.a4 = a4;
        this.correctAnswer = correctAnswer;
        this.query = query;
        this.selectedAnswer = selectedAnswer;
        this.correctness = correctness;
    }
    }
4b9b3361

Ответ 1

Вы должны изменить свой класс Question, чтобы фактически реализовать Parcelable. Интерфейс Parcelable может сбивать с толку сначала... но висеть там.

Есть два метода Parcelable, на которые вы должны обратить внимание:

  • writeToParcel(), который преобразует ваш класс в объект Parcel.
  • Question(Parcel in), который преобразует объект Parcel обратно в полезный экземпляр вашего класса.

Вы можете безопасно вырезать и вставлять другую Исходную информацию, которую я обозначил.

Для простоты я буду использовать только часть вашего класса Question:

public class Question implements Parcelable {
    String a1;
    String a2;
    ...

    public Question(String a1, String a1) {
        this.a1 = a1;
        this.a2 = a2;
    }

    // Your existing methods go here. (There is no need for me to re-write them.) 

    // The following methods that are required for using Parcelable
    private Question(Parcel in) {
        // This order must match the order in writeToParcel()
        a1 = in.readString();
        a2 = in.readString();
        // Continue doing this for the rest of your member data
    }

    public void writeToParcel(Parcel out, int flags) {
        // Again this order must match the Question(Parcel) constructor
        out.writeString(a1);
        out.writeString(a2);
        // Again continue doing this for the rest of your member data
    }

    // Just cut and paste this for now
    public int describeContents() {
        return 0;
    }

    // Just cut and paste this for now
    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];
        }
    };
}

Теперь измените то, как вы помещаете queries в свои дополнения Intent.

intent.putParcelableArrayListExtra("queries", queries);

То, как вы читаете Parcelable массив, является идеальным, как есть.

Ответ 2

Чтобы иметь возможность поставлять ArrayList как часть намерения, ваш тип должен реализовывать Parcelable. Судя по тому, что вам пришлось отдать свой список на (ArrayList<? extends Parcelable>), вы этого не сделали. Если бы у вас было, вы могли бы просто:

class Foo implements Parcelable {
//implementation here
}
ArrayList<Foo> foos = new ArrayList<Foo>();
new Intent().putParcelableArrayListExtra("foos", foos); //no need to cast