I have and Intent and I pass, from the MainActivity, two ArrayLists of Parcelables to a "FormActivity", that receives the ArrayLists perfeclty (using startActivityForResult), returns perfectly the data gathered throught the form.
The problem is that, if I click the button to open again the FormActivity, the two ArrayLists are not sent again, and I get a NullPointerException.
Have anyone ever seen this?
Thank you.
MainActivity code:
public void insertProductButtonClicked(View view){
Intent addProductIntent = new Intent(getBaseContext(), AddProductActivity.class);
addProductIntent.removeExtra("consumers");
addProductIntent.removeExtra("products");
addProductIntent.putParcelableArrayListExtra("consumers", consumers);
addProductIntent.putParcelableArrayListExtra("products", products);
startActivityForResult(addProductIntent, MyActivities.ACTIVITY_ADD_PRODUCT);
}
AddProductActivity code ("FormActivity"):
Intent intent = new Intent();
intent.putExtra("productName", productNameEditText.getText().toString());
intent.putExtra("productPrice", Double.valueOf(productPriceEditText.getText().toString()));
SparseBooleanArray checkedItems = consumersListView.getCheckedItemPositions();
ArrayList<Integer> consumersToAdd = new ArrayList<Integer>();
for (int i = 0; i < consumers.size(); i++) {
if (checkedItems.get(i)){
consumersToAdd.add(consumers.get(i).getId());
}
}
intent.putIntegerArrayListExtra("productConsumers", consumersToAdd);
setResult(Activity.RESULT_OK, intent);
finish();
You can declare your ArrayList as a static, check below...
public static ArrayList<String> array = new ArrayList<String>();
By doing this you can access your ArrayList from anywhere by type
activity_name.array;
where activity_name is the activity or class in which you declare the static ArrayList.
Good luck.
Related
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");
i have to transfer more then one string from one activity to another activity in android , i already know how to transfer one string from one to another string in android but for more then one string i can not found ways my code is here ,
if (long_insert_row_index>0){
//Spinner spDepCMPName = (Spinner) findViewById(R.id.spDepCMPName);
// String strCMP= spDepCMPName.getSelectedItem().toString();
//String strCMP=depositecmpname;
//startActivity(new Intent(DepositActivity.this, AuditPointDetailsActivity.class).putExtra("insert_row_index",""+long_insert_row_index).putExtra("segment_name", spinner_segment.getSelectedItem().toString()).putExtra("audit_type_name", spinner_audit_type.getSelectedItem().toString()).putExtra("audit_type_id", audit_type_id).putExtra("segment_id", segment_id));
///please see commented section at bottom
startActivity(new Intent(DepositActivity.this, DepositeNextActivity.class)
.putExtra("insert_row_index",""+long_insert_row_index)
.putExtra("CMPName", depositecmpname));
}else {
Toast.makeText(DepositActivity.this,"Error while inserting data.Please re-enter data.",Toast.LENGTH_LONG).show();
}
}
Now i want to send both string from one activity to another , i dont know how to do that one .
you can use code in your first activity like :-
ArrayList<String> arr = new ArrayList<String>();
arr.add(long_insert_row_index);
arr.add( depositecmpname);
Intent intent = new Intent(firstactivity.this,secondActivity.class);
intent.putExtra("array_list", arr);
startActivity(intent);
Now in another class you can use this code saying :-
Bundle extras = getIntent().getExtras();
ArrayList<String> arr = (ArrayList<String>)extras.getStringArrayList("array_list");
Toast.makeText(getApplicationContext(),""+arr.size(),Toast.LENGTH_LONG).show();
hope it will help
Use for open activity:
Intent intent = new Intent(activity, Activity2.class);
intent.putExtra("String1", "Hello!");
intent.putExtra("String2", "Hello!2")
activity.startActivity(intent);
In open activity:
getIntent.getStringExtra("String1");
getIntent.getStringExtra("String2");
Or use
intent.putExtra("StringByteArr", "str".toByteArray());
and:
String.valueOf(getIntent.getByteArrayExtra("StringByteArr"));
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
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();
I have an activity which has an array list
ArrayList<String> array = new ArrayList<String>();
i want this array list to be passed to another activity when a Save button is clicked, but i don't want that activity to start...
Usually this code helps in starting an activity
public void onClick(View v) {
if (v==Save)
{
Bundle bundle = new Bundle();
bundle.putStringArrayList("DONE", activeURL);
Intent myIntent = new Intent(Reader2.this, Aggregator.class);
myIntent.putExtra("reader2", activeURL);
startActivity(intent);
}
}
but i just want to pass the array and start another activity.
Can you please help me ?
Thanks in advance.
You can declare you ArrayList as a static one like this,
public static ArrayList<String> array = new ArrayList<String>();
By doing this you can access your ArrayList from anywhere by
activity_name.array;
where activity_name is the activity or class in which you declare the static ArrayList
you can pass an intent to already running activity.. follow this http://www.helloandroid.com/tutorials/communicating-between-running-activities for that
in the intent you can add an extra like this
Intent contactsIntent = new Intent(getApplicationContext(),
ContactCards.class);
contactsIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
appWidgetId);
//Bundle containing the serialized list
Bundle extraContacts = new Bundle();
//Putting the array list templist is the array list here
extraContacts.putSerializable("CONTACT_KEY", tempList);
extraContacts.putString("CALL_STRING", CALL_STRING);
contactsIntent.putExtras(extraContacts);
contactsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(contactsIntent);
Based on the fact that you mention a 'Save' button, I think you would rather save this data to SharedPreferences or an SQLiteDatabase.
I am unsure of what it would mean to 'save' some data to another Activity and not start it.
With your data in a persisted state, you should be able to access it from any one of your other Activity's, which is what is sounds like you are after.
use 1st activity
Intent i=new Intent(ArraylistpassActivity.this,second.class);
i.putStringArrayListExtra("key",arl);startActivity(i);
2nd activity:
arl=bundle.getStringArrayList("key");