Issue
I am coding an Android application that displays a RecyclerView with some elements and some CRUD operations. One thing I am trying to do is to update an existing element from my RecyclerView, and for that I open a new activity where I fill some textboxes and update in a database. After I finish() the update activity, the program returns to the previous one, but not before not executing any code that remained in the method I started the intent in the first place.
Here is the code:
Intent intent1 = new Intent(context, UpdateActivity.class);
Gson gson = new Gson();
String planeAsString = gson.toJson(plane);
intent1.putExtra("PlaneString", planeAsString);
context.startActivity(intent1);
Snackbar snackbar1 = Snackbar.make(v, "Element was updated", Snackbar.LENGTH_SHORT).setDuration(2000);
adapter.onIorUItem();
snackbar1.show();
break;
What should I do to be able to execute the code after the
context.startActivity(intent1);
line, after I finish the started activity. The code purpose is to show a snackbar and to call a method from the RecyclerView's adapter, so I can refresh the list. The following code is located in a class named PlaneHolder, which isn't an activity or fragment, the hierarchy of the calls being the next:
MainActivity -> FragmentOfMainActivity (here the recyclerView is located) -> PlaneAdapter -> PlaneHolder -> UpdateActivity (the activity where I update, and from where I want to return to PlaneHolder after I finish it).
Solution
When you call startActivity()
, the new Activity
isn't started right away. This is just a request to the Android framework to start the new Activity
. Your code continues to run to completion before anything will happen. Android can't start the new Activity
until your method completes and control is returned to the Android framework. That means your Snackbar
is shown immediately before Android starts the new Activity
. You probably just don't see it because it happens underneath the new Activity
. Add logging or set a breakpoint and you will see this.
To fix this, use the solution suggested by @denvercoder9: instead of startActivity()
use startActivityForResult()
and show your Snackbar
in onActivityResult()
.
Answered By - David Wasser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.