Yosi199
Yosi199

Reputation: 1804

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 be used?

I couldn't understand it from reading through either the PDFs or the android developers website.

Anyone care to explain it to me?

Upvotes: 1

Views: 238

Answers (2)

Nipuna
Nipuna

Reputation: 7026

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);

Upvotes: 0

Chris Thompson
Chris Thompson

Reputation: 35598

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?

Upvotes: 1

Related Questions