如何从一个在Android的使用意图的另一项活动通过对象的ArrayList?(How to pas

2019-06-21 07:44发布

我已在代码中我下面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();
       }

      }

Answer 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传递活动之间的数据

你已经创建时,这通常工作的DataModel

例如,假设我们有类型的JSON

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

这里的鸟是列表,它包含两个元素,因此

我们将使用创建模型jsonschema2pojo

现在我们有了模型类名称BirdModel和鸟BirdModel包括鸟的名单和伯德包含姓名和身​​份证

去鸟类,并添加接口“ 实现Parcelable”

添加implemets方法在Android Studio中通过Alt + Enter键

注意:会出现对话框说添加工具方法,然后按Enter键

按Alt +的Add 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");

谢谢

如果有任何问题,请让我知道。



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


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


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

这都行!



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

想想看,你要发送的一个场景arraylistbeanclass从类型Activity1Activity2
使用下面的代码

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

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



Answer 6:

如果你的类问题只包含原语 ,Serializeble字符串字段可以实现他Serializable接口 。 ArrayList的是实现Serializable,这就是为什么你可以把它像Bundle.putSerializable(键,值),并将其发送到另一个活动 。 恕我直言,Parcelable - 这是很长的路要走。



Answer 7:

我做的两件事情在这种情况下

  1. 实现序列化/反序列化系统,我的对象,并通过他们的字符串(JSON格式一般,但你可以序列化他们的任何您想要的方式)

  2. 实现一个可住的活动外,使我的所有活动,可以读取和写入到这个容器的容器。 您可以将此容器静态或使用某种依赖注入的每个活动来获取相同的实例。

Parcelable工作得很好,但我始终认为它是一个难看的格局并没有真正增加,如果你写的模型之外自己的序列码,是不是有什么价值。



Answer 8:

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

在接下来的活动,你可以检索你的这样的问题清单:

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

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


Answer 9:

您可以从一个活动通过捆绑意图通过数组列表到另一个。 使用下面的代码,这是通过ArrayList中的最短和最合适的方式

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



Answer 10:

你必须还需要实现Parcelable接口,必须以宗地的说法在构造函数中除了序列化添加writeToParcel方法对您的问题类。 否则应用程序会崩溃。



Answer 11:

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


Answer 12:

您可以使用物体通过比Serializable接口更有效parcelable。

请参阅我是共享包含完整parcelable样品的链接。 点击下载ParcelableSample.zip



Answer 13:

//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


Answer 14:

就那么简单 !! 工作对我来说

从活动

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

        startActivity(intent);

到活动

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


Answer 15:

要设置在科特林数据

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中



Answer 16:

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

从活性2获得额外的

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

    } 


Answer 17:

我有相同的问题,同时与仍hassling Parcelable ,我发现静态变量不为任务这样一个坏主意。

你可以简单地创建

public static ArrayList<Parliament> myObjects = .. 

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

我不知道什么公共静态变量与活动的应用程序上下文暗示。 如果您也有关于这个或这种方法的性能方面的疑问,请参考:

  • 什么是共享活动之间数据的最佳方式?
  • 使用Android中的静态变量

干杯。



文章来源: How to pass ArrayList of Objects from one to another activity using Intent in android?