Can someone explain to me the role of the Application class in android?
I'm studying Java and Android development by myself from PDFs. I'm trying to figure out what the Application
class is for, and when should it b开发者_JAVA技巧e used?
I couldn't understand it from reading through either the PDFs or the android developers website.
Anyone care to explain it to me?
The short answer is the Application
class is used to store any information that you need to persist across your activities. This could be anything from global settings to configuration to data structures, etc that you will access from multiple Activities
and that need to maintain some sort of state. Does that make sense?
Application class can be used to store things we used to store in sessions in web development. If your mobile app is related to shopping, you can store your shopping cart details in the Application class.
Your Application class
public class ApplicationState extends Application {
private ArrayList<CartItem> cartItems = new ArrayList<CartItem>();
public ArrayList<CartItem> getCartItems() {
return cartItems;
}
public void addCartItems(CartItem cartItem) {
this.cartItems.add(cartItem);
}
}
CartItem c = new CartItem();
ApplicationState appState =((ApplicationState)getApplicationContext());
appState.addCartItems(c);
精彩评论