Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton vs Intents (Android)

Tags:

java

android

I am going to make application more specifically a game for android phone.

I am going to have multiple activities and many classes so I'm thinking about storage of the game data.

Game data should be visible for activities so I'm thinking if I should rather use singleton to store data there and receive it easily from any activity or should I rather pass data using Intents?

There will be small amounts and large amounts of data (small such as score, large such as maps etc..).

For scores I would use intents but then wouldn't it be better to do everything the same way? And if yes I think one singleton with whole game state would be better. Any ideas?

like image 500
Taks Avatar asked Jul 10 '11 21:07

Taks


1 Answers

When I need data that is used by multiple activities I have just created a custom Application class and then used that as my "Singleton" and it works fine since every activity can then access the custom Application context

To do that start by creating and extended Application class

public class MyApplication extends Application {
  // Details left blank
}

Add this to your manifest so it knows to use that instead of the default application

 <application 
        ...
        android:name=".MyApplication"

Then add any custom methods that you want all of your activities to have access to, and from each activity use something like

((MyApplication)this.getApplicationContext()).myMethod()

You can also see Application for more details

like image 102
Idistic Avatar answered Nov 19 '22 06:11

Idistic