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

Как передать ArrayList объектов из одного в другое с использованием Intent в android?

У меня есть следующий код в моем методе onClick() как

 List<Question> mQuestionsList = QuestionBank.getQuestions();

Теперь у меня есть намерение после этой строки, как показано ниже:

  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putParcelableArrayListExtra("QuestionsExtra", (ArrayList<? extends Parcelable>) mQuestionsList);
  startActivity(resultIntent);

Я не знаю, как передать этот список вопросов в намерении от одного действия к другому действию Мой класс вопросов

public class Question {
    private int[] operands;
    private int[] choices;
    private int userAnswerIndex;

    public Question(int[] operands, int[] choices) {
        this.operands = operands;
        this.choices = choices;
        this.userAnswerIndex = -1;
    }

    public int[] getChoices() {
        return choices;
    }

    public void setChoices(int[] choices) {
        this.choices = choices;
    }

    public int[] getOperands() {
        return operands;
    }

    public void setOperands(int[] operands) {
        this.operands = operands;
    }

    public int getUserAnswerIndex() {
        return userAnswerIndex;
    }

    public void setUserAnswerIndex(int userAnswerIndex) {
        this.userAnswerIndex = userAnswerIndex;
    }

    public int getAnswer() {
        int answer = 0;
        for (int operand : operands) {
            answer += operand;
        }
        return answer;
    }

    public boolean isCorrect() {
        return getAnswer() == choices[this.userAnswerIndex];
    }

    public boolean hasAnswered() {
        return userAnswerIndex != -1;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        // Question
        builder.append("Question: ");
        for(int operand : operands) {
            builder.append(String.format("%d ", operand));
        }
        builder.append(System.getProperty("line.separator"));

        // Choices
        int answer = getAnswer();
        for (int choice : choices) {
            if (choice == answer) {
                builder.append(String.format("%d (A) ", choice));
            } else {
                builder.append(String.format("%d ", choice));
            }
        }
        return builder.toString();
       }

      }
4b9b3361

Ответ 1

Хорошо работает,

public class Question implements Serializable {
    private int[] operands;
    private int[] choices;
    private int userAnswerIndex;

   public Question(int[] operands, int[] choices) {
       this.operands = operands;
       this.choices = choices;
       this.userAnswerIndex = -1;
   }

   public int[] getChoices() {
       return choices;
   }

   public void setChoices(int[] choices) {
       this.choices = choices;
   }

   public int[] getOperands() {
       return operands;
   }

   public void setOperands(int[] operands) {
       this.operands = operands;
   }

   public int getUserAnswerIndex() {
       return userAnswerIndex;
   }

   public void setUserAnswerIndex(int userAnswerIndex) {
       this.userAnswerIndex = userAnswerIndex;
   }

   public int getAnswer() {
       int answer = 0;
       for (int operand : operands) {
           answer += operand;
       }
       return answer;
   }

   public boolean isCorrect() {
       return getAnswer() == choices[this.userAnswerIndex];
   }

   public boolean hasAnswered() {
       return userAnswerIndex != -1;
   }

   @Override
   public String toString() {
       StringBuilder builder = new StringBuilder();

       // Question
       builder.append("Question: ");
       for(int operand : operands) {
           builder.append(String.format("%d ", operand));
       }
       builder.append(System.getProperty("line.separator"));

       // Choices
       int answer = getAnswer();
       for (int choice : choices) {
           if (choice == answer) {
               builder.append(String.format("%d (A) ", choice));
           } else {
               builder.append(String.format("%d ", choice));
           }
       }
       return builder.toString();
     }
  }

В своей исходной деятельности используйте следующее:

  List<Question> mQuestionList = new ArrayList<Question>;
  mQuestionsList = QuestionBank.getQuestions();
  mQuestionList.add(new Question(ops1, choices1));

  Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
  intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);

В своей целевой деятельности используйте следующее:

  List<Question> questions = new ArrayList<Question>();
  questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");

Ответ 2

Между действиями: Работа для меня

ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);

В Transfer.class

Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");

Надеюсь, что это поможет кому-то.

Использование Parcelable для передачи данных между Activity

Это обычно работает, если вы создали DataModel

например. Предположим, что у нас есть json типа

{
    "bird": [{
        "id": 1,
        "name": "Chicken"
    }, {
        "id": 2,
        "name": "Eagle"
    }]
}

Здесь птица - это список и содержит два элемента, поэтому

мы создадим модели, используя jsonschema2pojo

Теперь у нас есть модельный класс Name BirdModel and Bird BirdModel состоит из списка птиц и Bird содержит имя и id

Перейдите в класс bird и добавьте интерфейс " реализует Parcelable"

добавить метод implemets в студию android с помощью Alt + Enter

Примечание. Появится диалоговое окно с надписью "Добавить метод" нажмите Enter

Добавлена ​​возможность добавления Parcelable, нажав Alt + Enter

Примечание. Появится диалоговое окно с надписью Add Parcelable и снова введите

Теперь, чтобы передать это намерению.

List<Bird> birds = birdModel.getBird();
Intent intent = new Intent(Current.this, Transfer.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Birds", birds);
intent.putExtras(bundle);
startActivity(intent);

А на операции переноса onCreate

List<Bird> challenge = this.getIntent().getExtras().getParcelableArrayList("Birds");

Спасибо

Если есть какие-либо проблемы, пожалуйста, дайте мне знать.

Ответ 3

Шаги:

  • Реализует класс объекта сериализуемым

    public class Question implements Serializable`
    
  • Поместите это в свою Исходную активность

    ArrayList<Question> mQuestionList = new ArrayList<Question>;
    mQuestionsList = QuestionBank.getQuestions();  
    mQuestionList.add(new Question(ops1, choices1));
    
    Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
    intent.putExtra("QuestionListExtra", mQuestionList);
    
  • Поместите это в свою целевую активность

     ArrayList<Question> questions = new ArrayList<Question>();
     questions = (ArrayList<Questions>) getIntent().getSerializableExtra("QuestionListExtra");
    

Ответ 4

Передайте свой объект через Parcelable. И вот хороший учебник, чтобы вы начали.
Первый вопрос должен реализовать Parcelable следующим образом и добавить эти строки:

public class Question implements Parcelable{
    public Question(Parcel in) {
        // put your data using = in.readString();
  this.operands = in.readString();;
    this.choices = in.readString();;
    this.userAnswerIndex = in.readString();;

    }

    public Question() {
    }

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

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

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

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

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

}

Затем передайте свои данные следующим образом:

Question question = new Question();
// put your data
  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putExtra("QuestionsExtra", question);
  startActivity(resultIntent);

И получите свои данные следующим образом:

Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
    question = extras.getParcelable("QuestionsExtra");
}

Это будет сделано!

Ответ 5

Класс bean или pojo должен implements parcelable interface.

Например:

public class BeanClass implements Parcelable{
    String name;
    int age;
    String sex;

    public BeanClass(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    } 
     public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
        @Override
        public BeanClass createFromParcel(Parcel in) {
            return new BeanClass(in);
        }

        @Override
        public BeanClass[] newArray(int size) {
            return new BeanClass[size];
        }
    };
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeString(sex);
    }
}

Рассмотрим сценарий, который вы хотите отправить arraylist типа beanclass из Activity1 в Activity2.
Используйте следующий код

Activity1:

ArrayList<BeanClass> list=new ArrayList<BeanClass>();

private ArrayList<BeanClass> getList() {
    for(int i=0;i<5;i++) {

        list.add(new BeanClass("xyz", 25, "M"));
    }
    return list;
}
private void gotoNextActivity() {
    Intent intent=new Intent(this,Activity2.class);
    /* Bundle args = new Bundle();
    args.putSerializable("ARRAYLIST",(Serializable)list);
    intent.putExtra("BUNDLE",args);*/

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("StudentDetails", list);
    intent.putExtras(bundle);
    startActivity(intent);
}

деятельности2:

ArrayList<BeanClass> listFromActivity1=new ArrayList<>();

listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");

if (listFromActivity1 != null) {

    Log.d("listis",""+listFromActivity1.toString());
}

Я думаю, что это основное, чтобы понять концепцию.

Ответ 6

Я делаю одну из двух вещей в этом сценарии

  • Внедрить сериализуемую/десериализованную систему для моих объектов и передать их как строки (в формате JSON обычно, но вы можете сериализовать их любым способом)

  • Внедрить контейнер, который живет за пределами действия, чтобы все мои действия могли читать и записывать в этот контейнер. Вы можете сделать этот контейнер статическим или использовать какую-либо инъекцию зависимости для извлечения одного и того же экземпляра в каждом действии.

Parcelable работает просто отлично, но я всегда считал его уродливым и не добавлял никакого значения, которого нет, если вы напишете собственный код сериализации вне модели.

Ответ 7

Если ваш класс Вопрос содержит только примитивы, поля Serializeble или String, вы можете реализовать его Serializable. ArrayList реализует Serializable, поэтому вы можете поместить его как Bundle.putSerializable(ключ, значение) и отправить его на другой Активность. IMHO, Parcelable - это очень длинный путь.

Ответ 8

Создание вашего намерения кажется правильным, если ваш Question реализует Parcelable.

В следующем упражнении вы можете получить список таких вопросов, как это:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

Ответ 9

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

bundle.putStringArrayList( "ключевое слово", ArrayList);

Ответ 10

Вам также необходимо реализовать интерфейс Parcelable и добавить метод writeToParcel к вашему классу вопросов с аргументом Parcel в Constructor в дополнение к Serializable. иначе приложение выйдет из строя.

Ответ 11

Ваш массив:

ArrayList<String> yourArray = new ArrayList<>();

Напишите этот код, откуда вы хотите:

Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);

В следующей операции:

ArrayList<String> myArray = new ArrayList<>();

Введите этот код в onCreate:

myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");

Ответ 12

Просто как тот !! работал на меня

От деятельности

        Intent intent = new Intent(Viewhirings.this, Informaall.class);
        intent.putStringArrayListExtra("list",nselectedfromadapter);

        startActivity(intent);

К деятельности

Bundle bundle = getIntent().getExtras();
    nselectedfromadapter= bundle.getStringArrayList("list");

Ответ 13

Вы можете использовать возможность передачи объекта, которая более эффективна, чем Serializable.

Просьба ссылаться на ссылку, которую я разделяю, содержит полный примерный образец. Нажмите на скачивание ParcelableSample.zip

Ответ 14

Вы можете передать Arraylist/Pojo, используя такой пакет,

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 

Получите эти значения в SecondActivity следующим образом

  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
  String filter = bundle.getString("imageSliders");

Ответ 15

Чтобы установить данные в kotlin

val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)

Чтобы получить данные

 val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?

Теперь доступ к архаисту

Ответ 16

  Реализует Parcelable и отправляет массив списков как putParcelableArrayListExtra и получает его из следующего действия getParcelableArrayListExtra

Пример:

Внедрите parcelable в свой пользовательский класс - (Alt +enter) Внедрите его методы

public class Model implements Parcelable {

private String Id;

public Model() {

}

protected Model(Parcel in) {
    Id= in.readString();       
}

public static final Creator<Model> CREATOR = new Creator<Model>() {
    @Override
    public ModelcreateFromParcel(Parcel in) {
        return new Model(in);
    }

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

public String getId() {
    return Id;
}

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


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

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

Передача объекта класса из упражнения 1

 Intent intent = new Intent(Activity1.this, Activity2.class);
            intent.putParcelableArrayListExtra("model", modelArrayList);
            startActivity(intent);

Получите дополнительную информацию от Activity2

if (getIntent().hasExtra("model")) {
        Intent intent = getIntent();
        cartArrayList = intent.getParcelableArrayListExtra("model");

    } 

Ответ 17

Использование ниже кода;

private ArrayList<AssignListPojo.AssignListObj> mDataset;

Сделайте свой класс класса реализуемым Serializable и передайте ваш arraylist, используя ниже код;

intent.putExtra("StringKey",mDataset);

и получить этот arraylist в другом действии, используя ниже код;

ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("StringKey");

Ответ 18

У меня был тот же самый вопрос, и, хотя я все еще беспокоюсь с Parcelable, я обнаружил, что статические переменные не являются такой плохой идеей для задачи.

Вы можете просто создать

public static ArrayList<Parliament> myObjects = .. 

и использовать его в другом месте через MyRefActivity.myObjects

Я не был уверен в том, что публичные статические переменные подразумевают в контексте приложения с действиями. Если вы также сомневаетесь в этом или в аспектах эффективности этого подхода, обратитесь к:

Приветствия.