Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

android - Where and how can I store data that is accessible from multiple Activities?

I am working on a card game (not usual 52 playing cards, but own cards with own values). I have 2 Activities, CardsToChoose and Deck.

My Problem right now is, that I can't figure out how to display the cards I choose in Deck. Where do I store the values of those cards, so that I can play with that Deck?

  • Tried with Intent, but gets way too complicated
  • Maybe it is possible with Objects, but I don't know how that works exactly...

Structure of my Cards (Not coded yet, because as said, I don't know where to put that code. Right know I only have a page with clickable ImageViews of my Cards ("CardsToChoose")):

Name: Card1
Value: score += 1 (If you play that card, the score goes up by 1)

I hope someone could explain how that works

question from:https://stackoverflow.com/questions/65852329/where-and-how-can-i-store-data-that-is-accessible-from-multiple-activities

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This case is for scenario when you want only 1 card:

If the Cards are not the usual 52 but still let's say you defined 3 cards, a,b and c. From Deck Activity you want to pick a card and move to CardsToChoose Activity You can create a separate file outside the Activity called Card.kt and store the data for the cards over there. Now, inside the Deck Activity, you can refer to these cards with an integer, let's say 1 for card a, 2 for card b and 3 for card c. Now when user is in Deck Activity and picks a card and wants to move to CardsToChoose Activity, you can pass this integer based on the Card he picked using the intent.putExtra("cardIndex", your_integer);

Now in the CardsToChoose Activity you can get the index from Intent.

For the case where you have multiple cardIndexes

For the case where you have multiple cardIndexes to be passed, you can either pass an array or use a ViewModel to share the data between activities. Here is how to pass an array of Integer Card Indices:

let's say 1 and 2 are selected card indices

int array[] = {1,2};

Intent i = new Intent(DeckActivity.this, CardsToChooseActivity.class);
i.putExtra("numbers", array);
startActivity(i);

and then you can receive the array in CardsToChooseActivity using:

Bundle extras = getIntent().getExtras();
int[] arrayB = extras.getIntArray("numbers");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...