send Arraylist by Intent - android

How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:
ArrayList<Song> songs;
How could I get this list inside Activity B?

The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).
Since you are trying to pass an ArrayList<Song>, you have two options.
The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);
The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);
So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?
It depends on which option you selected above. If you chose the first, you will write something that looks like this:
List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");
If you chose the second, you will write something that looks like this:
List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");
The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).

Misam is sending list of Songs so it can not use plain putStringArrayList(). Instead, Song class has to implement Parcelable interface. I already explained how to implement Parcelable painless in post here.
After implementing Parcelable interface just follow Uddhavs answer with small modifications:
// First activity, adding to bundle
bundle.putParcelableArrayListExtra("myArrayListKey", arrayList);
// Second activity, reading from bundle
ArrayList<Song> list = getIntent().getParcelableArrayListExtra("myArrayListKey");

I hope this helps you.
1. Your Song class should be implements Parcelable Class
public class Song implements Parcelable {
//Your setter and getter methods
}
2. Put your arraylist to putParcelableArrayListExtra()
public class ActivityA extends AppCompatActivity {
ArrayList<Song> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ActivityB.class)
.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) songs));
}
});
}
3. In the ActivityB
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
final ArrayList<Song> songs = intent.getParcelableArrayListExtra("songs");
//Check the value in the console
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (Song value : songs) {
System.out.println(value.getTitle());
}
}
});
}

to send a string arrayList in Java you can use,
intent.putStringArrayListExtra("key", skillist <- your arraylist);
and
List<String> listName = getIntent().getStringArrayListExtra("key");

Please note, bundle is one of the key components in Android system that is used for inter-component communications. All you have to think is how you can use put your Array inside that bundle.
Sending side (Activity A)
Intent intent1 = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
Parcelable[] arrayList = new Parcelable[10];
/* Note: you have to use writeToParcel() method to write different parameters values of your Song object */
/* you can add more string values in your arrayList */
bundle.putParcelableArray("myParcelableArray", arrayList);
intent1.putExtra("myBundle", bundle);
startActivity(intent1);
Receiving side (Activity B)
Bundle bundle2 = getIntent().getBundleExtra("myBundle"); /* you got the passsed bundle */
Parcelable[] arrayList2 = bundle.getParcelableArray("myParcelableArray");

Related

Unexpected behavior when passing parcelable data to other activity from an adapter

I have an Adapter which uses some custom object list. I wanted to pass the clicked object's to the other activity. So I made the object class implement Parcelable.
To send the data from the adapter
view.findViewById(R.id.play_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), YouTubePlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("data", movie));
intent.putExtras(bundle);
mContext.startActivity(intent);
To receive the data in the destination activity
Bundle b = getIntent().getExtras();
ArrayList<Video> videos = b.getParcelable("data");
But when I run it, it would pass nothing.
I tried passing other simpler values like strings and integer and they were too not passed.
Then I had to achieve the task by creating interface. And it worked. But I still don't understand this unexpected behavior when starting activity from adapters. Can you please answer the reason behind this unexpected behavior?

Simple manner pass arraylist between activity and intent

I am learning Android (I'm VERY newbie at the moment).
I was looking and reading another posts but I have not find this exactly (or not simple).
I want to pass a arraylist from an activity to a intent service, I think this is the simplest manner to do it; however I get NullPointer Exception.
public class MainActivity extends Activity {
private static final String TAG = "Main";
ArrayList<String> lista_actual = new ArrayList<String>();
...
public void onClick (View v) {
Intent msgIntent = new Intent(MainActivity.this, MiIntentService.class);
lista_actual.add("probasndo cad");
lista_actual.add("dfafsadf");
lista_actual.add("dfasf");
msgIntent.putStringArrayListExtra("lista", lista_actual);
msgIntent.putExtra("iteraciones", 10);
startService(msgIntent);
//copiar();
}});
Then where I try get the array:
protected void onHandleIntent(Intent intent)
{
ArrayList<String> lista_archivos = intent.getStringArrayListExtra("lista_actual");
Log.d ("Intent", Integer.toString(lista_archivos.size()));
.
.
.
Thanks.
While you are fetching your array list in intent service ur calling wrong key, it should be :
ArrayList<String> lista_archivos = intent.getStringArrayListExtra("lista");
Log.d ("Intent", Integer.toString(lista_archivos.size()));
Replace lista_actual with lista.
You need to serialize the arraylist in order to pass between activities. Further help will be found here. Hope that helps

Android: Passing an ArrayList between classes

How do I pass an ArrayList between classes? I want to pass an ArrayList from this class/method that extends Activity...
public class OpportunityActivity extends Activity {
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
startActivity(intent);
}
...over to OppListActivity class that extends ListActivity where I use this opportunities ArrayList to populate my custom ListView using the elements in the arraylist opportunities:
public class OppListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
I'd like to pass opportunities arraylist between the two intact. Should I...
- use a bundle (I've tried but can't work out the right syntax, and this seems like overkill/maybe there's a better way?)
- make opportunities public / somehow exposed to both classes
- pass opportunities as a parameter?
Specific syntax (not pseudocode) appreciated.
You can't create an Activity like this:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
OppListActivity a = new OppListActivity();
}
You should always use an Intent. In the Intent you can add an "extra" with your ArrayList, which you will read later in your ListActivity. Note that you will probably need to make your Opportunity implement Parcelable. There's a lot of info on both of these topics both in StackOverflow and in the official docs.
You need to use intents to start a new activity. And you can actually put serializable objects in your intent's extra data:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
intent.putExtra("opportunities", opportunities);
startActivity(intent);
}
And in your OppListActivity activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
ArrayList<Opportunity> opportunities = intent.getSerializableExtra("opportunities");
}
But you probably need to make sure that Opportunity class extends Serializable.
On way is to use putExtra if you are using an Intent to trigger the next activity. It would look something like this:
ArrayList<String> test_array = new ArrayList<String>();
// do something with test_array
Intent launchNextActivity = new Intent(getApplicationContext(), nextActivity.class);
launchNextActivity.putExtra("array", test_array);
startActivity(launchNextActivity);
And then in the activity you launch, you could use the following to get it:
Intent sender = getIntent();
ArrayList<String> passedInArray = new ArrayList<String>();
passedInArray = sender.getStringArrayExtra("array");
usually you add an extra bundle when starting a new intent when switching to some other activity. e.g
ArrayList<String> theArrayList = new ArrayList<String>();
Intent i = new Intent(this,TheNewActivity.class);
i.putStringArrayListExtra("list",theArrayList);
startActivity(i);
finish();
hiiii..... You can use Bean,with the one ArrayList
e.g
ArrayList<RowItem> aryListbean=new ArrayList<rowItem>(); //your arraylist
RowItem rowItem=new RowItem(); // that is your bean class
now You have to create a class RowItem,that is your Bean,which have getter/setter method
for(....)
{
rowItem.setUserId(); // set method's example
rowItem.setPassword() // set method's exampl
aryListbean.add(rowItem);
}
Now you can use your data in every Activities using getmethod
e.g
getUserId();
getUserPassword();

Problems sending data from one activity to another with application

As the title says I want to transfer data, in this case the information introduced by the user on an EditText and a Spinner, from one activity to another.
I am following a tutorial from a book but it doesn't work (I think its not complete). Here the code of the program:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
this.location=(EditText)findViewById(R.id.location);
this.cuisine=(Spinner)findViewById(R.id.cuisine);
this.grabReviews=(Button)findViewById(R.id.get_reviews_button);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.cuisine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
this.cuisine.setAdapter(adapter);
this.grabReviews.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
handleGetReviews();
}
}
);
}
private void handleGetReviews() {
RestaurantsActivity application= (RestaurantsActivity) getApplication();
application.setReviewCriteriaCuisine(this.cuisine.getSelectedItem().toString());
application.setReviewCriteriaLocation(this.location.getText().toString());
Intent intent=new Intent(Constants.INTENT_ACTION_VIEW_LIST);
startActivity(intent);
}
This code above doesn't work. I dont understand four things:
-RestaurantsActivity must be the actual activity right?
-In all the examples I have seen over the internet there is an application extends class, in this example there isnt.
-setReviewCriteria function is missing
-Where does Constants.INTENT_ACTION_VIEW_LIST come from ?
So your target is to get the data to Restaurantsactivity?
Normally data in android are handed over from one activtiy to another by using Intents.
So first you create an intent.
Then you put the data you want to transfer into the intent by using the intent.putExtra() method.
In the activity that gets the intent you can get the data by using getIntent().getExtra() method (getExtra can be something like getStringExtra()).
Here is a small example for a edit box called "name":
public void onCreate(Bundle iBundle){
//do some stuff here
//perhaps define some Buttos and so on
//now lets start the activity
Intent intent = new Intent(currentActivityname.this, ActivityYouWantToStart.class);
intent.putExtra("name", name.getText().toString())
startActivity(intent); // you can also start an startActivityForResult() here :)
}
In our receiving activity you can now handle the intent (e.g. in the onCreate() method
public void onCreate(Bundle iBundle){
String name = this.getIntent().getStringExtra("name",some default value);
}
Try to put data in the Bundle and start Activity with this Bundle
Intent intent = new Intent(this, YourSecondActivity.class);
intent.putExtra(... HERE YOUR BUNDLE WITH DATA ...);
startActivity(intent);
Hope, it help you!

How to pass checked items to another activity?

I got list of checked contacts.However, i need to pass these selected contacts to another activity and display in edit Text.Please help.Thanks
You have a few solutions...
You can use static fields in your Java classes
You can pack the data into Intents via Intent.putExtra
Option (1) is probably going to be the easiest and quickest if you are trying to send data between your own activities. Option (2) is what you must do if you wish to send data to Activities of another applications.
I suggest you read these Q&A first though as some cover this question in more depth...
Passing data of a non-primitive type between activities in android
Passing data between activities in Android
Switching activities/passing data between activities
You have to use an Intent to do so.
Example, to pass the data to an activity already running:
public void sendToActivity(Object data){
Intent i = new Intent("SEND_DATA");
i.putExtra("data", this.catchReports.get(data));
sendBroadcast(i);
}
Then, you have to setup a listener in your receiving activity to catch the Broadcasted signal:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Sets the View of the Activity
setContentView(R.layout.activity_layout);
registerReceiver(new CustomReceiver(this), new IntentFilter("SEND_DATA"));
}
With the following customreceiver:
public class CustomReceiver extends BroadcastReceiver {
private MyActivity activity;
public ReceiverEvent(MyActivity activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.doWhateverWithYourData(i.getParcelableExtra("newEvent"));
}
}
Note that if you want to transport Objects other than integers, floats and strings, you have to make them Parcelable.

Categories

Resources