如何在android中使用Intent将对象的ArrayList从一个传递给另一个活动?

问题描述 投票:23回答:17

我在onClick()方法的代码中有以下内容

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

现在我有了这一行后的意图,如下:

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

我不知道如何将这个问题列表从一个活动传递到另一个活动My Question类

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
17个回答
50
投票

活动之间:为我工作

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

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

我们将使用jsonschema2pojo创建模型

现在我们有模型类Name BirdModel和Bird BirdModel组成的Bird和Bird列表包含name和id

转到bird类并添加接口“implements Parcelable”

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

注意:将出现一个对话框,指出Add implements方法按Enter键

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

并且关于转移活动onCreate

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

谢谢

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


1
投票

您还必须实现Parcelable接口,除了Serializable之外,还必须在构造函数中使用Parcel参数将writeToParcel方法添加到Questions类中。否则应用程序将崩溃。


1
投票

你的arrayList:

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

1
投票

就那么简单 !!为我工作

从活动

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

        startActivity(intent);

参加活动

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

0
投票

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

请参考我所分享的链接包含完整的parcelable样本。 Click download ParcelableSample.zip


0
投票
//arraylist/Pojo you can Pass using bundle  like this 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 


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

//Happy coding

0
投票

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

现在访问arraylist


0
投票

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

    } 

-2
投票

我有完全相同的问题,虽然仍然讨厌Parcelable,我发现静态变量对于任务来说并不是一个坏主意。

你可以简单地创建一个

public static ArrayList<Parliament> myObjects = .. 

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

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

干杯。


23
投票

脚步:

  1. 将您的对象类实现为可序列化 public class Question implements Serializable`
  2. 把它放在你的Source Activity中 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");

18
投票

效果很好,

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

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

这样做!


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

考虑一个场景,您想将arraylistbeanclassActivity1发送到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());
}

我认为这是理解这个概念的基础。


2
投票

如果您的类Question仅包含基元,Serializeble或String字段,则可以实现Serializable。 ArrayList是实现Serializable的,这就是为什么你可以像Bundle.putSerializable(key, value)一样把它发送到另一个Activity。恕我直言,Parcelable - 这是非常漫长的道路。


2
投票

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

  1. 为我的对象实现一个序列化/反序列化系统并将它们作为字符串传递(通常以JSON格式,但你可以按照你想要的任何方式序列化它们)
  2. 实现一个位于活动之外的容器,以便我的所有活动都可以读取和写入此容器。您可以将此容器设置为静态或使用某种依赖项注入来检索每个活动中的相同实例。

Parcelable工作正常,但我总是发现它看起来很难看,如果你在模型之外编写自己的序列化代码,它并没有真正添加任何不存在的值。


1
投票

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

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

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

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

1
投票

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

bundle.putStringArrayList( “关键字”,数组列表);

© www.soinside.com 2019 - 2024. All rights reserved.