Question

Let's assume I have a class MainActivity.

This contains a number of objects stored in fields, such as instances of Player, Enemy, Level, etc. Each of these objects needs to be able to refer to every other object.

What is the best way to go about this?

  1. Make these fields static, and refer to them accordingly, i.e.

    MainActivity.player.setHealth(0);
    
  2. Create getter methods for each field, and simply pass each object a reference to MainActivity, so that they can call these getter methods, i.e.

    mainActivity.getPlayer().setHealth(0);
    
  3. Pass each object a reference to every other object, and store these references in fields within each object, so that they can be referred to directly, i.e.

     player.setHealth(0);
    
Was it helpful?

Solution

Not a real answer but just to give you some tips.

Your Player should be like so:

public class Player
{
    private static Player _player = null;
    int _health;
    ...

    public static Player getInstance()
    {
        if (_player == null)
            _player = new Player(...);

        return _player;
    }

    public void increaseHealth(int amount)
    {
        _health += amount;
    }
 }

Then in any part of your application when you need a Player you can do:

Player p = Player.getInstance();

and you will get the same player all the time. You can do a similar thing with your level class as only 1 level will be active at any one time.

However the Enemy class will need a different approach. I would make a List inside the Level class and get at them like so:

Level l = Level.getInstance();
List<Enemy> enemiesOnLevel = l.getEnemies();
// do something with them

OTHER TIPS

Have a look in the Android docs here: http://developer.android.com/guide/faq/framework.html#3. There is also the possibility to serialize your object into primitive datatypes and pass those within your Intent to the new Activity.

A couple more options to share objects between activities are to use parcable, which I think is probably the highest performance method, and shared preferences.

In my app I used to learn (the little I know about android programming), I used gson to serialize the object to json, then stored it in shared preferences in activity A , then recreated it from shared preferences in activity B, and then stored it again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top