How to put a List in intent - android

I have a List in one of my activities and need to pass it to the next activity.
private List<Item> selectedData;
I tried putting this in intent by :
intent.putExtra("selectedData", selectedData);
But it is not working. What can be done?

Like howettl mentioned in a comment, if you make the object you are keeping in your list serializeable then it become very easy. Then you can put it in a Bundle which you can then put in the intent. Here is an example:
class ExampleClass implements Serializable {
public String toString() {
return "I am a class";
}
}
... */ Where you wanna create the activity /*
ExampleClass e = new ExampleClass();
ArrayList<ExampleClass> l = new ArrayList<>();
l.add(e);
Intent i = new Intent();
Bundle b = new Bundle();
b.putSerializeable(l);
i.putExtra("LIST", b);
startActivity(i);

You have to instantiate the List to a concrete type first. List itself is an interface.
If you implement the Parcelable interface in your object then you can use the putParcelableArrayListExtra() method to add it to the Intent.

i think ur item should be parcelable. and you should use arraylist instead of list.
then use intent.putParcelableArrayListExtra

This is what worked for me.
//first create the list to put objects
private ArrayList<ItemCreate> itemsList = new ArrayList<>();
//on the sender activity
//add items to list where necessary also make sure the Class model ItemCreate implements Serializable
itemsList.add(theInstanceOfItemCreates);
Intent goToActivity = new Intent(MainActivity.this, SecondActivity.class);
goToActivity.putExtra("ITEMS", itemsList);
startActivity(goToActivity);
//then on second activity
Intent i = getIntent();
receivedItemsList = (ArrayList<ItemCreate>) i.getSerializableExtra("ITEMS");
Log.d("Print Items Count", receivedItemsList.size()+"");
for (Received item:
receivedItemList) {
Log.d("Print Item name: ", item.getName() + "");
}
I hope it works for you too.

Everyone says that you can use Serializable, but none mentioned that you can just cast the value to Serializable instead of list.
intent.putExtra("selectedData", (Serializable) selectedData);
Core's lists implementations already implement Serializable, so you're not bound to a specific implementation of list, but remember that you still can catch ClassCastException.

Related

passing list throug intent to another activity

I am trying to pass list to next activity but its giving me classcast exception how can i solve it?I am implementing serializable in model class.
Someone help me in resolving the issue.
List<PagesSqliteData>pagesSqliteDataArrayList = new ArrayList<>();
PagesSqliteData pagesSqlite = new PagesSqliteData();
pagesSqlite.setToc_name(bookingsSqliteDataArrayList.get(position).getToc_name());
pagesSqlite.setCompletion(bookingsSqliteDataArrayList.get(position).getCompletion());
pagesSqlite.setCategory_id(bookingsSqliteDataArrayList.get(position).getCategory_id());
pagesSqlite.setBooking_id(bookingsSqliteDataArrayList.get(position).getBooking_id());
pagesSqlite.setTable_of_content_id(bookingsSqliteDataArrayList.get(position).getTable_of_content_id());
pagesSqliteDataArrayList.add(pagesSqlite);
Intent i = new Intent(MyBookings.this, Pages.class);
i.putExtra("LIST",pagesSqliteDataArrayList);
startActivity(i);
}
Fetching like this in next activity:
PagesSqliteData details = (PagesSqliteData)getIntent().getSerializableExtra("LIST");
You get a ClassCastException for one simple reason. Look at this commented version of your code:
List<PagesSqliteData>pagesSqliteDataArrayList = new ArrayList<>();//HERE YOU CREATE AN ARRAYLIST!!!
PagesSqliteData pagesSqlite = new PagesSqliteData();
pagesSqlite.setToc_name(bookingsSqliteDataArrayList.get(position).getToc_name());
pagesSqlite.setCompletion(bookingsSqliteDataArrayList.get(position).getCompletion());
pagesSqlite.setCategory_id(bookingsSqliteDataArrayList.get(position).getCategory_id());
pagesSqlite.setBooking_id(bookingsSqliteDataArrayList.get(position).getBooking_id());
pagesSqlite.setTable_of_content_id(bookingsSqliteDataArrayList.get(position).getTable_of_content_id());
pagesSqliteDataArrayList.add(pagesSqlite);
Intent i = new Intent(MyBookings.this, Pages.class);
i.putExtra("LIST",pagesSqliteDataArrayList);
startActivity(i);
And when you load:
PagesSqliteData details = (PagesSqliteData)getIntent().getSerializableExtra("LIST");//HERE IT IS SUDDENLY A SINGLE OBJECT
So when you save, ignore the arrayList. Pass pagesSqlite instead. And make sure this class is either Serializable or Parcelable. Or when you load, load it into an ArrayList. What you do is equivalent to:
PagesSqliteData data = new ArrayList<PagesSqliteData>();
And that is something you can't do.

Trying to send List object to another activity

I am trying to send a List<Question> to other activity but I am receiving the error "java.util.ArrayList cannot be cast to android.os.Parcelable".
FirstActivity
List<Question> list;
list = response.body().items;
Intent myIntent = new Intent(SearchActivity.this, RestaurantActivity.class);
myIntent.putExtra("restaurants", (Parcelable) list);
SearchActivity.this.startActivity(myIntent);
SecondActivity
Intent intent = getIntent();
List<Question> restaurants = intent.getExtras().getParcelable("restaurants");
textView = (TextView)findViewById(R.id.textView);
textView.setText(restaurants.get(0).title);
What is the problem?
The reason it doesn't work is that ArrayList itself does not implement the Parcelable interface. However, some Android classes like Intent and Bundle have been set up to handle ArrayLists provided that the instances they contain are of a class which does implement Parcelable.
So, instead of putExtra, try using the putParcelableArrayListExtra method instead.
You'll need to use get getParcelableArrayListExtra on the other side.
Be aware that this only works with ArrayLists, and the Question class will need to implement Parcelable.

passing a list of data from one intent to another using serializable

I would like to parse a list of data from one intent to another intent
However, with my code,
I'm only manage to pass the first item in the listview .
I use a log.d to check for the items, and realised that only one items is being pass.
In my listview there's 2 items,when I pass it over to my next intent, only one item was shown in the log..
I did a serializable in my class.
I make a log in my summary,
however,
when I click on summary, the log that was shown in not all the data.
logcat:
01-28 18:20:49.218: D/Bundle(20278): bundle : Bundle[{clickedpreOdometer=, clickedID=2, clickedCost= 12.0, clickedDate=27/12/2014, pojoArrayList=[com.example.fuellogproject.fuelLogPojo#43bf3f18, com.example.fuellogproject.fuelLogPojo#43bf5b68], clickedPump=3, clickedPrice=4, clickedFCon= 0.0, clickedOdometer=3}]
listview
public void summaryClick (View v)
{
Intent sum = new Intent(this, summary.class);
fuelLogPojo clickedObject = pojoArrayList.get(0);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedID", clickedObject.getid());
dataBundle.putString("clickedDate", clickedObject.getdate());
dataBundle.putString("clickedPrice", clickedObject.getprice());
dataBundle.putString("clickedPump", clickedObject.getpump());
dataBundle.putString("clickedCost", clickedObject.getcost());
dataBundle.putString("clickedOdometer", clickedObject.getodometer());
dataBundle.putString("clickedpreOdometer",
clickedObject.getpreodometer());
dataBundle.putString("clickedFCon", clickedObject.getfcon());
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
Log.i("FuelLog", "dataBundle " + dataBundle);
// Attach the bundled data to the intent
// sum.putExtras(dataBundle);
sum.putExtras(dataBundle);
Log.i("Exrrass", "dataBundle " + dataBundle);
// Start the Activity
startActivity(sum);
}
summary.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
//month = (TextView)findViewById(R.id.month);
avgPrice = (TextView)findViewById(R.id.showavfPriceTV);
exFuel = (TextView)findViewById(R.id.showexFuelTV);
avgFC = (TextView)findViewById(R.id.showavgFCTV);
doneButton = (Button)findViewById(R.id.doneBTN);
exitButton = (Button)findViewById(R.id.exitBTN);
Bundle takeBundledData = getIntent().getExtras();
// First we need to get the bundle data that pass from the UndergraduateListActivity
bundleID = takeBundledData.getString("clickedID");
/*bundleDate = takeBundledData.getString("clickedDate");
bundlePrice = takeBundledData.getString("clickedPrice");
bundlePump = takeBundledData.getString("clickedPump");
bundleCost = takeBundledData.getString("clickedCost");
bundleOdometer = takeBundledData.getString("clickedOdometer");
bundlePreOdometer = takeBundledData.getString("clickedpreOdometer");
bundleFcon = takeBundledData.getString("clickedFCon");*/
Log.d("Bundle","bundle : "+ takeBundledData);
}
fuelLogpojo.java
public class fuelLogPojo implements Serializable{
fuelLogPojo should implement either Parcelable or Serializable
Bundles can accept custom classes, if they implement either Parcelable or Serializable, Parcelable is faster but more work to implement and Serializable is easier to implement, but slower.
I'm going to imagine that fuelLogPojo extends Serializable in this example, just because its easier to setup but you should really consider Parcelable
Then you can do this:
dataBundle.putSerializable("pojoArrayList", pojoArrayList);
sum.setArguments(bundle);
Also, you should reconsider the naming convention for your classes.
EDIT:
Here's how to access that pojoArrayList in summary.
List<fuelLogPojo> pojoArrayList = (List<fuelLogPojo>)extras.getSerializable("pojoArrayList");
If you want to pass array of Custom Objects You have to implements Parcerable interface
Take a look here
And then pass array like
Intent i=...
i.putParcelableArrayListExtra("ARRAY", array);
and read it
getIntent().getParcelableArrayListExtra("ARRAY")

Can't pass an ArrayList<Parcelable> to an activity

This is the code
ArrayList<MyObject> list = new ArrayList<MyObject>();
list.add(new MyObject());
Intent intent = new Intent(this, ReceiverActivity.class);
intent.putExtra("list", list);
startActivity(intent);
ReceiverActivity
List<MyObject> list = (List<MyObject>)getIntent().getExtras().getParcelable("list");
Here list is null. Also this doesn't work:
List<MyObject> list = (List<MyObject>)getIntent().getExtras().getSerializable("list");
MyObject is Parcelable, I implemented all required methods. I guess this implementation is not the problem, because otherwise I would recive other kind of exceptions. But I don't get anything besides list is null.
Thanks in advance...
Now I found this:
List<Parcelable> list = (List<Parcelable>)getIntent().getParcelableArrayListExtra("list");
that has to be used in the receiver activity, but how do I send it and how do I get List<MyObject> from List<Parcelable> ?
USe i.putParcelableArrayListExtra(name, value) where i is your intent. Dont use putExtra() for a parcelable ArrayList.
Try:
ArrayList<MyObject> myList = extras.<MyObject>getParcelableArrayList("list"));

How to pass object to an activity?

I have two activities, NewTransferMyOwn.java and FromAccount.java
When I go from NewTransferMyOwn.java to FromAccount.java, I do write code as following
Intent i = new Intent(NewTransferMyOwn.this, FromAccount.class);
startActivityForResult(i, FROM_ACCOUNT);
When I do come back from FromAccount.java to NewTransferMyOwn.java, then I want to pass a complete object of class Statement
I do write code as
Statement st = ItemArray.get(arg2);//ItemArray is ArrayList<Statement>, arg2 is int
Intent intent = new Intent(FromAccount.this,NewTransferMyOwn.class).putExtra("myCustomerObj",st);
I do get error as following on putExtra,
Change to 'getIntExtra'
as I do, there is again casting st to int, what is issue over here, how can I pass Statement object towards back to acitivity?
You can also implement your custom class by Serializable and pass the custom Object,
public class MyCustomClass implements Serializable
{
// getter and setters
}
And then pass the Custom Object with the Intent.
intent.putExtra("myobj",customObj);
To retrieve your Object
Custom custom = (Custom) data.getSerializableExtra("myobj");
UPDATE:
To pass your custom Object to the previous Activity while you are using startActivityForResult
Intent data = new Intent();
Custom value = new Custom();
value.setName("StackOverflow");
data.putExtra("myobj", value);
setResult(Activity.RESULT_OK, data);
finish();
To retrieve the custom Object on the Previous Activity
if(requestCode == MyRequestCode){
if(resultCode == Activity.RESULT_OK){
Custom custom = (Custom) data.getSerializableExtra("myobj");
Log.d("My data", custom.getName()) ;
finish();
}
}
You can't pass arbitrary objects between activities. The only data you can pass as extras/in a bundle are either fundamental types or Parcelable objects.
And Parcelables are basically objects that can be serialized/deserialized to/from a string.
You can also consider passing only the URI refering to the content and re-fetching it in the other activity.

Categories

Resources