I am moving from activity A to B.I want that on click of a button in activity B i should go back to activity A and it should be refreshed(i am doing an api call in activity A).However if user is moving back from B to A by just backpressed on device it should NOT be refreshed.Is there any better way of doing this without recreating activity A?
6 Answers
You could start activity B with Intent.startActivityForResult() and answer this request on your Button clickListener.
OnBackPress default behaviour won't do anything to your previous activity.
Please, be aware of life cycles.
Another ways of handling this is: - Using singletons provided by your Application class. - SharedPreferences updates handling on onResume (of Activity A).
Force yourself on using Fragments for small projects.
Regards,

- 346
- 1
- 7
You can do it easily by using LocalBroadcastManager. Have a look on this thread
how to use LocalBroadcastManager?
https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
No and yes. Activity A has no normal way of knowing how Activity B was ended. But you can send something from B back to A an other way. See answer from @Masum

- 2,109
- 6
- 24
- 46
Yes. If you want the Activity
A to be refreshed, just launch it again via an startActivity(new Intent(this, A.class))
.
If you don't want A to be refreshed, then call finish()
method in Activity
B.
For example, call finish()
in onBackPressed
in Activity B.

- 6,770
- 9
- 33
- 62
The best solution i think is to use onRestart()
@Override
public void onRestart() {
super.onRestart();
//the activity is restared when click back and you could add what do you want for refresh here.
}

- 1,494
- 13
- 15
Okey i just remembered EventBus
. I think you can use event based solution .
In your activity A ,in onCreate
and onStart
add this line :
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
And add this @Subscribe
method to your activity A :
@Subscribe
public void onMessageEvent(MyEvent event){
//handle event
//if any data coming handle data
//trigger recreating methods etc ...
}
Create new class like that :
public class MyEvent {
//you can add any values to send datas another activity
public MyEvent (){
}
}
And in your activity B in Button's onClick
method :
EventBus.getDefault().post(new MyEvent());
Add this to your dependencies :
compile 'org.greenrobot:eventbus:3.0.0'

- 6,573
- 5
- 40
- 58