I know how to pass a variable from one activity to another using global variables.
e.g.
In one.java:
GlobalVars.setColour(0);
In two.java:
if (GlobalVars.getColour() == 0) ...
GlobalVariables.java:
private static int colour2;
public static int getColour() {
return colour2;
}
public static void setColour(int colour) {
colour2 = colour;
}
What if i have an array in one.java and i need it in another class?
ArrayList myArr = new ArrayList();
myArr is uploaded with contacts from the phone book of the phone, so it is dynamic. I need it to upload a ListView with its elements in a custom dialog class. How to pass it to another activity/dialog?
解决方案
The method you have chosen (creating a static instance) WILL work for an object like ArrayList in the same fashion as you did with the primitive (this is creating a Singleton).
However, in most cases creating static fields just to pass data between Activities is definitely not recommended. Both primitive data and ArrayList can be passed as extras in the Intent you use to start another Activity.
private ArrayList mArray;
private String mString;
private int mValue;
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("arrayListExtra", mArray);
intent.putExtra("stringExtra", mString);
intent.putExtra("intExtra", mValue);
startActivity(intent);
All of these data types (and more) can be seamlessly passed in an Intent. Then, you can access them on the other side as follows:
Intent intent = getIntent();
ArrayList array = intent.getStringArrayListExtra("arrayListExtra");
String string = intent.getStringExtra("stringExtra");
int value = intent.getIntExtra("intExtra", 0);
If you are passing the data to a Dialog then you can call a setter method and pass anything you want without worrying about the boundaries that exist between Activities. For instance, with a custom Dialog implement a method in your dialog so you can set the value before displaying it.
public class MyDialog extends Dialog {
private ArrayList mItems;
//All other methods of the dialog here
public void setItems(ArrayList items) {
mItems = items;
}
}
Then, in whichever method of your Activity you plan to create and show the Dialog do
//theArray is your ArrayList with data.
MyDialog dialog = new MyDialog();
dialog.setItems(theArray);
dialog.show();
Notice that this is how you would pass a list of items to an AlertDialog for display. These dialogs also have methods like setItems() to pass data in before showing it. If you're Activity manages the dialog for you (you're calling showDialog() from the Activity), call the setter in onCreateDialog() or onPrepareDialog()...whichever is more appropriate.
Hope that helps!