Cast ArrayList to String

1

I am receiving an arrangement from one Activity to another as follows:

List<Producto> productos = new ArrayList<Producto>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_carrito);

    productos = (ArrayList<Producto>) getIntent().getSerializableExtra("Productos");

and it does not mark me an error, but when executing it, it sends me this error.

  

java.lang.String can not be cast to java.util.ArrayList

How do I solve it?

    
asked by J. Torres 15.10.2016 в 03:44
source

3 answers

1

According to your error message:

  

java.lang.String can not be cast to java.util.ArrayList

Surely you are sending a String and you try to convert it to ArrayList type when you receive it.

 productos = (ArrayList<Producto>) getIntent().getSerializableExtra("Productos");

If you go to sending an ArrayList of Product objects from one Activity to another is done in this way .

Create your ArrayList of Product objects and send it in Intent with .putExtra() :

   Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("Productos", productos);
                startActivity(intent);

To receive the ArrayList of Product objects in the second Activity, it is done in the following way:

ArrayList<Producto> lista = (ArrayList<Producto>) getIntent().getSerializableExtra("Productos");

Something very important that you need is that your Producto object should implement the Serializable class :

public class Producto implements Serializable {
    
answered by 15.10.2016 / 06:45
source
0

I've been a little away from Android but looking at the documentation of Intent I see that the method you use returns a Serializable object. Try using the getStringArrayExtra (String name) method instead of getSerializableExtra (String name). There is also the method getStringArrayListExtra (String name), which returns an object of type ArrayList, this object can not be converted to ArrayList but you can treat the array that returns you and insert new instances of Product in your product array.

    
answered by 15.10.2016 в 03:56
0

In the activity that sends the information

Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("Productos", ArrayList<Producto>productos);

In the activity you receive, it should be like this:

  ArrayList<Producto> productos = new ArrayList<Producto>();
  productos = (ArrayList<Producto>)getIntent().getSerializableExtra("Productos");
    
answered by 15.10.2016 в 04:27