Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Serialization/Object Passing and Returning

So I have an app that manages workorders. In one part of the app, I have a list of workorders that has been retrieved from a web service. The user then picks one of the workorders from the list and the list starts a new activity (passing the Workorder object to it) that shows the workorder details. The user can edit parts of the workorder during this time. If the user returns to the list (via the back button), I need to pass the modified workorder BACK to the workorder list and either update or replace the old object with the new modified one. Otherwise, (as is currently happening) the user edits the workorder, but if they go back to the list and select the same workorder again, the workorder detail activty shows all the old data. What is the best way to do this. Currently I have the Workorder class implement Serializable so the workorder objects can be passed to successive activities.

So this works: List -> Workorder A

But this is where I'm having the issue: List <- Workorder A (modified)

I'm not sure if I should be using startActivtyForResult and passing the workorder object back or not. I know it's a possibility, but I'm not sure if there are more graceful ways to do this. Thanks for any and all help as it is greatly appreciated!

like image 263
D.R. Avatar asked Dec 28 '22 13:12

D.R.


1 Answers

If your Workorder object is already Serializable you could easily pass the object within the Bundle of an intent. To save the object to an intent you would do:

intent.putExtra("SomeUniqueKey", [intance of workorder]);

and to load in another activity:

Workorder workorder = (Workorder) intent.getSerializableExtra("SomeUniqueKey");

If you are using startActivityForResult it would go as such:

WorkorderListActivity.java:

Intent intent = new Intent(this, WorkorderDetailsActivity.class);
intent.putExtra("SomeUniqueKey", _workorder);
startActivityForResult(intent, [UniqueNumber]);

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
     if (requestCode == [UniqueNumber])
     {
         if (resultCode == RESULT_OK)
         {
             Workorder workorder = (Workorder) intent.getSerializableExtra("SomeUniqueKey");
             // Do whatever with the updated object
         }
     }
 }

WorkorderDetailsActivity.java:

public void onCreate(Bundle savedInstanceState)
{
     Bundle bundle = getIntent().getExtras();
     _workorder = (Workorder) bundle.getSerializable("SomeUniqueKey");
     // Display the object
}

public void onBackPressed()
{
    // Update _workorder object
    Intent intent = getIntent();
    intent.putExtra("SomeUniqueKey", _workorder);
    setResult(RESULT_OK, intent);
}

I believe this should work.

like image 129
Alex Avatar answered Jan 11 '23 01:01

Alex