50

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

      }
4

20 回答 20

84

活动之间:为我工作

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 和 Bird BirdModel 由 Bird 列表组成,Bird 包含 name 和 id

转到鸟类并添加接口“ implements Parcelable

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

注意:会出现一个对话框,说 Add implements method press Enter

通过按 Alt + Enter 添加 Parcelable 实现

注意:会出现一个对话框,说 Add Parcelable implementation 并再次 Enter

现在将其传递给意图。

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

谢谢

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

于 2014-07-08T11:28:04.463 回答
36

脚步:

  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");
    
于 2015-05-15T17:59:21.853 回答
24

它运作良好,

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");
于 2012-11-29T00:13:10.210 回答
10

你的 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的场景。 使用以下代码beanclassActivity1Activity2

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

我觉得这个基本理解概念。

于 2018-02-06T13:05:48.550 回答
7

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

这会做!

于 2012-11-28T09:35:27.090 回答
6

使用意图传递 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);
    

您也可以在类型中使用对象而不是字符串

为我工作..

于 2020-08-20T05:02:01.320 回答
5

就那么简单 !!为我工作

从活动

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

        startActivity(intent);

活动

Bundle bundle = getIntent().getExtras();
    nselectedfromadapter= bundle.getStringArrayList("list");
于 2018-09-05T02:17:57.910 回答
3

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

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

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

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

于 2012-11-28T09:42:03.273 回答
3

如果您的类Question仅包含原语SerializebleString字段,您可以实现他Serializable。ArrayList 是实现Serializable,这就是为什么你可以把它像Bundle.putSerializable(key, value)一样,然后发送到另一个Activity。恕我直言,Parcelable - 这是很长的路要走。

于 2012-11-28T09:47:27.510 回答
2

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

于 2015-01-17T01:51:24.603 回答
2

你的数组列表:

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");
于 2018-01-31T08:11:09.503 回答
2

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

现在访问数组列表

于 2018-10-16T10:26:16.303 回答
2

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

    } 
于 2019-04-25T07:17:36.793 回答
1

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

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

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

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}
于 2012-11-28T09:39:13.393 回答
1

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

bundle.putStringArrayList("关键字",arraylist);

于 2012-11-28T10:13:17.560 回答
1

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

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。

于 2020-07-31T09:21:58.400 回答
0

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

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

于 2018-06-07T13:06:43.653 回答
0

您可以使用这样的捆绑包传递 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");
于 2018-08-29T10:35:31.050 回答
0

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

不要忘记将值初始化到 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");
于 2021-11-26T13:59:29.977 回答
-2

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

您可以简单地创建一个

public static ArrayList<Parliament> myObjects = .. 

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

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

干杯。

于 2015-02-02T15:06:52.040 回答