添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
细心的乒乓球  ·  解决Type error: Invalid ...·  1 年前    · 
温文尔雅的罐头  ·  mysql source ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to pass an arrayList to another activity using intents. Here is the code in the first activity.

case R.id.editButton:
        Toast.makeText(this, "edit was clicked", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(this, editList.class);
        intent.putStringArrayListExtra("stock_list", stock_list);
        startActivity(intent);
        break;

This is where I try to retrieve the list in the second activity. Is something wrong here?

Intent i = new Intent(); //This should be getIntent();
    stock_list = new ArrayList<String>();
    stock_list = i.getStringArrayListExtra("stock_list");

The way you have it you've just created a new empty intent without any extras.

If you only have a single extra you can condense this down to:

stock_list = getIntent().getStringArrayListExtra("stock_list");
  • Add compile 'com.google.code.gson:gson:2.2.4' in dependencies block build.gradle.

  • Click on Sync Project with Gradle Files

  • Cars.java:

    public class Cars {
        public String id, name;
    

    FirstActivity.java

    When you want to pass ArrayList:

    List<Cars> cars= new ArrayList<Cars>();
    cars.add(getCarModel("1", "A"));
    cars.add(getCarModel("2", "B"));
    cars.add(getCarModel("3", "C"));
    cars.add(getCarModel("4", "D"));
    Gson gson = new Gson();
    String jsonCars = gson.toJson(cars);
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    intent.putExtra("list_as_string", jsonCars);
    startActivity(intent);
    

    Get CarsModel by Function:

    private Cars getCarModel(String id, String name){
           Cars cars = new Cars();
           cars.id = id;
           cars.name = name;
        return cars;
    

    SecondActivity.java

    You have to import java.lang.reflect.Type ;

    on onCreate() to retrieve ArrayList:

    String carListAsString = getIntent().getStringExtra("list_as_string");
    Gson gson = new Gson();
    Type type = new TypeToken<List<Cars>>(){}.getType();
    List<Cars> carsList = gson.fromJson(carListAsString, type);
    for (Cars cars : carsList){
       Log.i("Car Data", cars.id+"-"+cars.name);
    

    Hope this will save time, I saved it.

    Or you can simply have your Cars model class implement Parcelable interface and simply do intent.putParcelableArrayListExtra("parecelable_list", carsList); where carsList is an instance of ArrayList<Cars> – Nouman Hanif Dec 12, 2015 at 19:47 Why would I use Gson if there is already intent.putStringArrayListExtra, intent.getStringArrayListExtra or getSerializableExtra exists. And what if I use eclipse? I have to download and add Gson library? – Tushar Monirul May 18, 2016 at 18:47 My 2 bits... You can't down vote this for that reason, but you should recommend Parceling over Serializing as its been proved many times over - for Android its more efficient & out performs Serialization. – user3833732 Oct 17, 2019 at 10:48

    Receiving Intent Like :

    aListModel = (ArrayList<Model>) getIntent().getSerializableExtra(KEY);
    

    MUST REMEMBER:

    Here Model-class must be implemented like: ModelClass implements Serializable

    Normally like Sending Intent for startActivityForResult: Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(intent, aListModel); – Dhruv Raval Sep 4, 2015 at 4:36

    Suppose you need to pass an arraylist of following class from current activity to next activity // class of the objects those in the arraylist // remember to implement the class from Serializable interface // Serializable means it converts the object into stream of bytes and helps to transfer that object

    public class Question implements Serializable {
    

    in your current activity you probably have an ArrayList as follows

    ArrayList<Question> qsList = new ArrayList<>();
    qsList.add(new Question(1));
    qsList.add(new Question(2));
    qsList.add(new Question(3));
    // intialize Bundle instance
    Bundle b = new Bundle();
    // putting questions list into the bundle .. as key value pair.
    // so you can retrieve the arrayList with this key
    b.putSerializable("questions", (Serializable) qsList);
    Intent i = new Intent(CurrentActivity.this, NextActivity.class);
    i.putExtras(b);
    startActivity(i);
    

    in order to get the arraylist within the next activity

    //get the bundle
    Bundle b = getIntent().getExtras();
    //getting the arraylist from the key
    ArrayList<Question> q = (ArrayList<Question>) b.getSerializable("questions");
    
    //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
                    It is throwing an exception:  java.lang.ClassCastException: com.example.ModelObjectNameHere cannot be cast to java.io.Serializable
    – Ali Tamoor
                    Feb 17, 2021 at 7:26
    

    and create a new Intent that put Bundle to Intent

    Intent intent=new Intent(ActivityOne.this,ActivityTwo.class);
    intent.putExtras(bundle);
    startActivity(intent);
    

    for receive bundle insert this code

    Bundle bundle = getIntent().getExtras();
    ArrayList<StructMain> item = (ArrayList<StructMain>) bundle.getSerializable("test");
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.