Zujiry Zujiry - 11 months ago 36
Android Question

Saving and accessing a static variable in android activities

We are building an application atm in which you can change the rules for a game and start the game from the mainmenuactivity

Looks like this:

MainMenu - RuleList -RuleEdit (Rule management)
- PlayerActiivty - DrawCard (Game)

And we are also creating cards in the class GameLogic with a static array in it where the 13 cardtypes are saved with their rules.

So when we are changing the rule for a card we are calling
GameLogic.setRuleNumber(int pos,int ruleNumber) //pos is the position of the card in the cardArray

Problem is:
When we are creating the cards and start the game the cards are created and saved in GameLogic and if you enter the game now you can go through all the cards.
But if you go back to choose the MainMenu (it changes right to it) the cardArray is suddenly empty and when you are entering the game again it is empty, but still accessible so not null.

GameLogic cards

public class GameLogic {
public final static List<ICard> cards = new ArrayList<>();

public void createCards() {
DatabaseConnector dbc = new DatabaseConnector(context);
int rankLength = ICard.Rank.values().length;
int suitLength = ICard.Suit.values().length;
int ruleNumber;
ArrayList<IRule> rules = dbc.getAllRules();
int a = 0;
for (int i = 0; i < rankLength; i++) {
for (int j = 0; j < suitLength; j++) {
ruleNumber = rules.get(i).getRuleNumber();
cards.add((suitLength * i + j), new Card(ICard.Rank.values()[i], ICard.Suit.values()[j], ruleNumber));

Creating cards happens in the Menu:

//Main Menu Activity
protected void onCreate(Bundle savedInstanceState) {
GameLogic gameLogic = new GameLogic(this); //Creating the GameLogic we want to work with
gameLogic.createCards(); //Creating the cards

DrawCard Activity:

protected void onCreate(Bundle savedInstanceState) {

dbc = new DatabaseConnector(this);

//init deck

//init playerlist
playerList = CreatePlayer.playerList;
playerNameText = (TextView) findViewById(R.id.activePlayerName);

//init rule
ruleList = dbc.getAllRules();

public void initDeck() {
cardStack = GameLogic.getCardStack();

What is happening here between the different activities?
The problem is that in there are values saved in the Cards so we through an Intent we would have to give 5 different arrays. We don't think thats an appropriate solution.

Thanks for your help :)

Answer Source

I highly recommend this library to store data in a persistent manner.

Example key-value pair write:

Paper.book().write("key", value);

Example read:

Object value = Paper.book().read("key");