【问题标题】:How to pass ArrayList of Objects from one to another activity using Intent in android?如何在android中使用Intent将对象的ArrayList从一个活动传递到另一个活动?
【发布时间】:2012-11-16 02:46:51
【问题描述】:

我的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();
       }

      }

【问题讨论】:

标签: android android-intent parcelable


【解决方案1】:

活动之间:为我工作

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"
    }]
}

这里的bird是一个List,它包含两个元素

我们将使用jsonschema2pojo创建模型

现在我们有了模型类 Name BirdModel 和 Bird BirdModel 由鸟类列表组成 和 Bird 包含名称和 id

进入小鸟类,添加接口“implements Parcelable

通过 Alt+Enter 在 android studio 中添加实现方法

注意:会出现一个对话框,说 Add implements method 按回车

按 Alt + Enter 添加 Parcelable 实现

注意:会出现一个对话框,说添加 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);

在创建时转移活动

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

谢谢

如果有任何问题,请告诉我。

【讨论】:

  • 这个解决方案对我不起作用...请帮助@Somir Saikia
  • 你能详细说明什么不起作用吗?我有上面提到的两个解决方案。
  • 非常有帮助,感谢您的这篇文章!
【解决方案2】:

步骤:

  1. 将您的对象类实现为可序列化

    public class Question implements Serializable`
    
  2. 把它放在你的源活动

    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);
    
  3. 将其放入您的目标活动

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

【讨论】:

  • 虽然速度很慢,但效果很好。查看其他建议,他们说 Parcelable 更快。但这是很多工作。现在我只打算使用这个解决方案。
【解决方案3】:

效果很好,

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");

【讨论】:

    【解决方案4】:

    你的 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);
        }
    }
    

    考虑一个场景,您希望将beanclass 类型的arraylistActivity1 发送到Activity2
    使用以下代码

    活动1:

    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());
    }
    

    我认为这个基本理解概念。

    【讨论】:

    • public BeanClass createFromParcel(Parcel in) { return new BeanClass(in);我在这个 return new BeanClass(in); 上遇到错误
    • (ArrayList&lt;? extends Parcelable&gt;) 这个转换必须完成,比如bundle.putParcelableArrayList(testKey, (ArrayList&lt;? extends Parcelable&gt;) testList);
    【解决方案5】:

    通过 Parcelable 传递您的对象。 这里有一个good tutorial 可以帮助您入门。
    第一个问题应该像这样实现 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");
    }
    

    这样就可以了!

    【讨论】:

    • 没错,再详细一点
    • @hotveryspicy,好的会试试的。
    • 操作数和选择都是原始类型数组,如何读写parcelable
    【解决方案6】:

    使用 Intent 传递 ArrayList 的最简单方法

    1. 在依赖块 build.gradle 中添加这一行。

      implementation 'com.google.code.gson:gson:2.2.4'
      
    2. 传递数组列表

      ArrayList<String> listPrivate = new ArrayList<>();
      
      
      Intent intent = new Intent(MainActivity.this, ListActivity.class);
      intent.putExtra("private_list", new Gson().toJson(listPrivate));
      startActivity(intent);
      
    3. 在另一个活动中检索列表

      ArrayList<String> listPrivate = new ArrayList<>();
      
      Type type = new TypeToken<List<String>>() {
      }.getType();
      listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
      

    你也可以在类型中使用对象来代替字符串

    为我工作..

    【讨论】:

      【解决方案7】:

      就这么简单!!为我工作

      来自活动

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

      TO活动

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

      【讨论】:

      • putStringArrayListExtra 仅适用于 类型的 ArrayList
      【解决方案8】:

      如果你的类 Question 只包含 primitivesSerializebleString 字段,你可以实现他Serializable . ArrayList 是实现Serializable,这就是为什么你可以把它写成Bundle.putSerializable(key, value) 并将它发送到另一个Activity。 恕我直言,Parcelable - 这是很长的路要走。

      【讨论】:

        【解决方案9】:

        在这种情况下,我会做两件事中的一件

        1. 为我的对象实现一个序列化/反序列化系统并将它们作为字符串传递(通常采用 JSON 格式,但您可以以任何您喜欢的方式对其进行序列化)

        2. 实现一个位于活动之外的容器,以便我的所有活动都可以读取和写入此容器。您可以将此容器设为静态或使用某种依赖注入来检索每个活动中的相同实例。

        Parcelable 工作得很好,但我总是发现它是一种丑陋的模式,如果你在模型之外编写自己的序列化代码,它并没有真正增加任何价值。

        【讨论】:

        • 对选项 2 感到好奇,您将如何实现它?全局单例?
        • @Singularity 我个人使用我自己的非常轻量级的依赖容器。我将它开源并放在 Github 上的一个库中:github.com/aguynamedrich/beacon-utils README 有一些基本的代码示例,我很乐意离线进一步讨论。其他人使用 RoboGuice 来做这种事情,我相信还有很多其他人。 RoboGuice 有一个非常活跃的社区,使用非常广泛。
        • @Rich 我尽可能使用选项 1。在几乎所有情况下,它都与 JSON 兼容。对于大块数据来说这不是很好,JSON 处理很慢,但它比尝试使用 parcelable 模式要痛苦得多。..
        【解决方案10】:

        您还必须实现 Parcelable 接口,并且除了 Serializable 之外,还必须将 writeToParcel 方法添加到您的 Questions 类中,并在 Constructor 中使用 Parcel 参数。否则应用会崩溃。

        【讨论】:

          【解决方案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】:

            在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>?
            

            现在访问数组列表

            【讨论】:

              【解决方案13】:

              实现 Parcelable 并将 arraylist 发送为 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");
              
                  } 
              

              【讨论】:

                【解决方案14】:

                如果您的 Question 实现 Parcelable,您的意图创建似乎是正确的。

                在下一个活动中,您可以检索您的问题列表,如下所示:

                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                
                    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
                        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
                    }
                }
                

                【讨论】:

                  【解决方案15】:

                  您可以通过使用带有意图的 bundle 将数组列表从一个活动传递到另一个活动。 使用下面的代码 这是传递arraylist的最短和最合适的方式

                  bundle.putStringArrayList("keyword",arraylist);

                  【讨论】:

                    【解决方案16】:

                    我发现大多数答案都有效,但带有警告。所以我有一个巧妙的方法可以在没有任何警告的情况下实现这一点。

                    ArrayList<Question> questionList = new ArrayList<>();
                    ...
                    Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
                    for (int i = 0; i < questionList.size(); i++) {
                        Question question = questionList.get(i);
                        intent.putExtra("question" + i, question);
                    }
                    startActivity(intent);
                    

                    现在在第二个活动中

                    ArrayList<Question> questionList = new ArrayList<>();
                    
                    Intent intent = getIntent();
                    int i = 0;
                    while (intent.hasExtra("question" + i)){
                        Question model = (Question) intent.getSerializableExtra("question" + i);
                        questionList.add(model);
                        i++;
                    }
                    

                    注意: 在您的 Question 类中实现 Serializable。

                    【讨论】:

                      【解决方案17】:

                      您可以使用 parcelable 进行对象传递,这比 Serializable 更有效。

                      请参考我分享的链接,其中包含完整的可打包样本。 Click download ParcelableSample.zip

                      【讨论】:

                        【解决方案18】:

                        你可以像这样使用 bundle 传递 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");
                        

                        【讨论】:

                          【解决方案19】:

                          你可以试试这个。我想它会对你有所帮助。

                          不要忘记将值初始化到 ArrayList 中

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

                          使用intent.putStringArrayListExtra()发送数据....

                           Intent intent = new Intent(this, NextActivity.class);
                                          intent.putStringArrayListExtra("IMAGE_LIST", imageList);
                                          startActivity(intent);
                          

                          使用intent.getStringArrayListExtra()接收数据...

                          ArrayList<String> imageList = new ArrayList<>();
                          Intent intent = getIntent();
                                  imageList = intent.getStringArrayListExtra("IMAGE_LIST");
                          

                          【讨论】:

                            【解决方案20】:

                            我也有同样的问题,虽然还在纠结Parcelable,但我发现静态变量对于这项任务来说并不是一个坏主意。

                            你可以简单地创建一个

                            public static ArrayList<Parliament> myObjects = .. 
                            

                            并通过MyRefActivity.myObjects从其他地方使用它

                            我不确定公共静态变量在具有活动的应用程序的上下文中意味着什么。如果您对此方法或此方法的性能方面也有疑问,请参阅:

                            干杯。

                            【讨论】:

                              猜你喜欢
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2021-03-15
                              • 1970-01-01
                              • 1970-01-01
                              • 2018-10-10
                              • 2015-02-08
                              • 2011-02-13
                              相关资源
                              最近更新 更多