0

I am making a frisbee logger and have an ArrayList of Team objects. Each Team has an ArrayList of Player objects. Everything is using Serializable properly to be sent using Intent.

In my main activity I am displaying the list of Team objects in a ListView and an option to add another Team (only a name is needed). Once a Team is selected I pass the object to another activity using Intent. On this second activity I have it display the list of Player objects and have fields to enter another player object into the passed list.

When I return to the main activity and go back to the add Player activity, what I have added is gone.

I cannot use static because there is obviously more than one Team object. I think passing back the changed ArrayList could work but that seems a little lame, time-consuming, and frustrating.

Is there a built-in way in Android Studio that does this or am I on my own?

Note: I am not using SQLite as suggested in the comments

There's not a whole lot to show on this but here it is I guess:

MainActivity.java

private static ArrayList<Team> listOfTeams = new ArrayList<>();
private static ArrayList<Game> listOfGames = new ArrayList<>();
private ListView gameList, teamList;

.....

teamList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Team t = (Team)teamList.getItemAtPosition(position);
        viewTeam(t);
    }
});

.....

//Item select in teamList. Start the TeamViewActivity
public void viewTeam(Team t)
{
    Intent i = new Intent(this, TeamViewActivity.class);
    i.putExtra("teamView",t);
    startActivity(i);
}

TeamViewActivity.java

private Team team;
private ListView rosterList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_team_view);

    rosterList = (ListView) findViewById(R.id.playerList);

    Intent i = getIntent();
    Bundle extras = i.getExtras();

    if(extras!=null)
    {
        if(extras.get("teamView")!=null)
        {
            team = (Team) extras.get("teamView");
        }
    }

    populateRosterList(team.getRoster());
}

public void addPlayerToRoster(View view)
{
    String checkFirst = ((EditText) findViewById(R.id.firstText)).getText().toString();
    String checkLast = ((EditText) findViewById(R.id.lastText)).getText().toString();
    String checkNumber = ((EditText) findViewById(R.id.numberText)).getText().toString();

    if(!checkNumber.equals(""))
    {
        team.addPlayer(checkFirst, checkLast, Integer.parseInt(checkNumber));

        ((EditText) findViewById(R.id.firstText)).setText("");
        ((EditText) findViewById(R.id.lastText)).setText("");
        ((EditText) findViewById(R.id.numberText)).setText("");

        populateRosterList(team.getRoster());
    }
}

public void returnToMain(View view)
{
    Intent i = new Intent(this, MainActivity.class);
    i.putExtra("teamView", team);
    startActivity(i);
}

private void populateRosterList(ArrayList<Player> list)
{
    ArrayAdapter<Player> adapter = new ArrayAdapter<>(this,
            R.layout.activity_list, R.id.genericText, list);
    rosterList.setAdapter(adapter);
}

4 Answers4

0

in your case, you can use startActivityForResult instead of startActivity, then get your modified Team object from onActivityResult(int requestCode, int resultCode, Intent data) to update your list. startActivityForResult example

Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
0

As @Kingfisher Phuoc mentioned you could use srartActivityForResult in case you don't want to change your approach.

Otherwise I will suggest you use either :

  1. SharedPreference to store your arraylist object (by converting the arraylist to json then store it as string in json format). In the PlayerActivity you retrieve the data, manipulate it then save it. see this post

  2. SQLite

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ctu
  • 308
  • 4
  • 12
0

You can use fragments. You hold the list in the MainActivity and pass its reference to ShowListFragment and AddPlayerFragment by interfaces. And you can also do other operations over them. If you dont want to use json or sqlite it can be a good way for you.

MainActivity.java

public class MainActivity extends Activity implements ShowListener{
   public interface ShowListener{
       ArrayList<Team> getTeamList();
   }

   private ArrayList<Team> listOfTeams = new ArrayList<>();

   @Override
   public ArrayList<Team> getTeamList() {
    return listOfTeams;
   }

}

ShowListFragment.java

public class ShowListFragment extends Fragment {

private ArrayList<Team> listOfTeams;
private ShowListener listener;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener = (ShowListener)getActivity();
        listOfTeams = listener.getTeamList();
    }

}
misman
  • 1,347
  • 3
  • 21
  • 39
0

Consider your concept:

You serialize an object, i.e. you transform it into a transferrable format which is then copied over to the other activity and reconstructed as a new instance.

Consequently, you alter another instance, which is not available in the previous activity, if you do not return it - again, serialized - and finally reconstruct and copy it back into the respective instance.

What you need is a shared memory storage in your application, which can alter and retrieve data cross-activity OR a proper data routing using Intents w/ ISerializable.

Options:

  1. Always serialize objects and pass and copy them around. -> No multithreaded alteration, possibly slow, unbeautiful
  2. Singleton application with global data storage ir Context Object (I do NOT recommend the due to memory management and Garbage Collection inbetween Activity Switches BUT for consistency I'd wanted to mention this option)
  3. SQLite3 -> Quick, Simple and Scalable, But a bit cumbersome to get started with
  4. Any other file-structure stored and maintained in the data folder -> I'd expect a lot of boilerplate code here, and low performance
  5. Webservice and remote database
  6. Proper component setup, i.e. initialize all accessing components in your software with the appropriate reference to the data structs using for example fragments (Thanks to @mismanc, I actually missed that option initially)

In general you could abstract all that away using services and repositories, which allows you to under-the-hood test options like 3. 4. And 5. and find your best solution, and in addition, keeo the accessing code simple and clean.

MABVT
  • 1,350
  • 10
  • 17
  • 1
    Using RealmDB, SQLBrite, or other sqlite libraries makes the Sqlite option less cumbersome – OneCricketeer Nov 20 '16 at 06:44
  • Thanks for the whole options list! I think I might have to go look into SQLite. I've seen it before but I haven't really used it myself. Some concurrency would be a nice addition so I might as well go for it – PurpleWatermelun Nov 21 '16 at 01:11
  • Please consider @cricket_007 recommendations for integrating Sqlite! – MABVT Nov 21 '16 at 04:33