How to refresh fragments 'onResume?' - java

I want to refresh fragments from an Actvitiy. (Let's call the activity A)
Activity A contains the fragments.
When I finish Activity B then Activity A should refresh the fragments.
I was thinking this would be done in onResume? I tried simply restarting the activity through an intent but that's not usability friendly.
So how do I refresh fragments when I resume an activity?

Just put this code inside
onResume()
For example you want to update your listview when u return to your fregment.
#Override
public void onResume() {
super.onResume();
if (allowRefresh)
{
allowRefresh = false;
lst_applist = db.load_apps();
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
Here getFragmentManager().beginTransaction().detach(this).attach(this).commit();
This line detach and re-attach the fragment so your content will be updated.

The onResume() get called always before the fragment is displayed. Even when the fragment is created for the first time . So you can simply move your from onViewCreated() to onResume.
#Override
public void onResume() {
super.onResume();
//move your code from onViewCreated() here
}

I agree with Mehul But u can alse do it this way .if you want to replace your fragment you could just say
#Override
public void onResume() {
super.onResume();
if (allowRefresh)
{
allowRefresh = false;
lst_applist = db.load_apps();
getFragmentManager().beginTransaction().replace(Fragment_Container,fragment).commit();
}
}

Related

onPause() without intent , onResume() without onCreate()

I'm building an app that plays music on the background with service. The music is muted when the user is not in the app and unmuted when he is back. I used the onPause() and onResume() methods to do this.
The problem is - every time the user enters a new activity, the music pauses for a second and then resumes, because for a second the current activity is paused.
another problem - for the first run of the activity, the onResume() and onCreate() both works, which makes my service stops from the onResume() without it even being created from the onCreate() (which makes the app shut down).
is there a way to use onPause() without the intent part (or another similar way?)
is there a way to use onCreate() without to onResume() on the first run?
protected void onCreate(Bundle savedInstanceState) {
counter++;
if (counter==1) {
alliesSPEditor.putBoolean("isAllies", true);
alliesSPEditor.commit();
startService(new Intent(this,MusicService.class));
}
#Override
protected void onPause() {
super.onPause();
MusicService.getMP().mute();
}
#Override
protected void onResume() {
super.onResume();
if (counter!=1) //because the counter is still 1, the app won't shut down this way but it will not unmute the music.
MusicService.getMP().unMute();
}
onResume() is always called after onCreate() before the activity starts running
See https://developer.android.com/guide/components/activities/activity-lifecycle
I see some ways to solve this:
the problem is - every time the user enters a new activity, the music pauses for a second and then resumes, because for a second the current activity is paused
The first is you set a flag in the handler that start your new activity and
check in your onPause() method the value of de flag, if false, do nothing othewise mute de music.
public static boolean openOtherActivity = false;
#Override
protected void onPause() {
super.onPause();
if (!openOtherActivity) {
MusicService.getMP().mute();
}
}
You can use Preferences too if you preferrer
To resolve de onCreate() and onResume() problem, you can use the same logic
creates a flag for the services started and control when you needs unmute the music in anothers methods
public static boolean isServiceCreated = false; // In your activity that start the service
protected void onCreate(Bundle savedInstanceState) {
counter++;
if (counter==1) {
alliesSPEditor.putBoolean("isAllies", true);
alliesSPEditor.commit();
startService(new Intent(this,MusicService.class));
isServiceCreated = true; // set the flag to true
}
}
OnResume() method you can check if the service is started an create your logic

How to prevent the user to switch the fragment if data is edited?

I have a profile settings fragment. When the user edits anything without saving and trying to switch to another fragment it should prevent it and show a dialog. I used to do that on activity by overriding onBackPressed method. In a fragment, I've used onDetach but it crashes when I put the super in the if statement.
#Override
public void onDetach() {
if (isProfileChanged) {
super.onDetach();
}
}
onDetach() is lifecycle method its Called when the fragment is no longer attached to its activity. So i.e its meant to get called once you replace or remove the current fragment .
Apart from it you want to restrict user from changing fragment. You should validate the fields and make a decision weather to change fragment or not.
Do this in Activity's onBackPressed(). below is an example illustrating the same for reference .
#Override
public void onBackPressed() {
Fragment fragment =getSupportFragmentManager().findFragmentById(R.id.containerFrame);
if (fragment != null && fragment instanceof YourFragment) {
if(((YourFragment) fragment).validate()){
finish();
}
} else {
super.onBackPressed();
}
}
Create a public method in fragment and validate the field and return true/false. Make the use of same method to transaction further .

Android onCreate() not working

I'm having a strange problem to do with stopping my android app. On my phone I have a home button and a back button, now when I go into my app after pressing the home button, the program loads data from the internet as expected, but when I go into my app after pressing the back button, the data doesn't load. I've debugged it to an extent, and have found out that the only difference is that the back button calls the onCreate() method. I'm quite confused to why this is is happening.
Here's some of my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("DAP", "Created");
setContentView(R.layout.activity_ltc);
getActionBar().setTitle("LTC Charts");
getActionBar().setLogo(
getResources().getDrawable(R.drawable.new_litecoin_logo_large));
TextView textView = (TextView) findViewById(R.id.ltcdata);
textView.setText("Loading data...");
TimerTask timer = new TimerTask() {
#Override
public void run() {
parseJSON();
}
};
Timer time = new Timer();
time.schedule(timer, 500, 85);
}
"when I go into my app after pressing the back button, the data doesn't load."
If you have already launched your app, the Activity will be paused (and onPause is called) when you navigate away from it. When you navigate back to the app, the same activity instance is resumed (and onResume is called).
See http://developer.android.com/training/basics/activity-lifecycle/index.html
This is because your activity hasnt been destroyed. What you should do is put something into the onresume of your activity to get the data again when you come back to the activity. If you want the data to be destroyed for sure and the user never leaves the activity you can destroy everything in onpause.
As others said, override onResume().
A common pattern would be to extract common initialisation code into a method, and call it from where needed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
#Override
protected void onResume(){
super.onResume();
init();
}
private void init(){
setContentView(R.layout.activity_ltc);
getActionBar().setTitle("LTC Charts");
// ....
}
This could be because your activity is not set correctly at AndroidManifest.xml .
Make sure the activity name is the right one. If you inserted your activity into some package include that name as well . for example I have my activitu which is called "SettingsActivity" (usually the default is MainActivity) set in a package called Activities :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<activity android:name=".Activities.SettingsActivity">
...
Use the on resume function below.
#Override
public void onResume(){
//will be executed onResume
}

Videoview not starting when the user comes back to activity

I'm starting a project and I want to reproduce a video in the main activity when the app is executed, when the user presses the video it goes to another activity. If the user press the back button, he is going to the main screen again and reproduces the video from the beginning. The video is located in the raw directory.
The problem is that the videoview is reproducing the video when the activity is first created but not when the user goes back to it from the other activity (In my case the MenuSection activity). The code is really simple but i will paste it anyway:
public class MainActivity extends Activity {
private VideoView mVideoView;
LinearLayout menuSection;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +"/"+R.raw.documentariesandyou));
mVideoView.requestFocus();
mVideoView.setMediaController(null); //i dont want the controls of the videoview.
mVideoView.start();
menuSection = (LinearLayout) findViewById(R.id.menuSection);
menuSection.setOnClickListener(new menuSectionListener());
}
class menuSectionListener implements OnClickListener {
public void onClick(View v) {
Intent staticActivityIntent = new Intent(MainActivity.this, MenuSection.class);
startActivity(staticActivityIntent);
}
}
}
The MenuSection is just an activity that shows a textview like "Hello world", so I'm not pasting it.
Move mVideoView.start(); to onResume() instead of onCreate() as:
#Override
protected void onResume() {
super.onResume();
mVideoView.start();
}
see Managing the Activity Lifecycle onResume() is called from your Activity when Activity is Already Running
call video.pause() on onPause() overrided method of your activity and call video.resume() on onResume() method of your activity.
Move mVideoView.start(); to onStart(), instead of onCreate().
See Activity Lifecycle in the developer docs for more info on how the lifecycle of Activities work.
I am not certain, but you may also need to move the setVideoURI(); to onStart() as well.

OnResume() not called by Pressing back Button in ActivityGroup

As ActivityGroup manages the Activities in the form of view, so when I try to return back to the Parent Activity that called the child Activity in ActivityGroup the onResume() is not being called.
I tried calling the OnResume() like this.
((Activity)view.getContext()).onResume();
But its not working, instead finish() is working is fine for me.
((Activity)view.getContext()).finish();
So, I am able to get the Activity from the View, but not able to call the onResume(), any idea will be appreciable.
Try this, when you press back button using ActivityGroup.
public void back()
{
if ( arrList.size() > 1 )
{
arrList.remove(arrList.size() - 1);
View v = arrList.get(arrList.size() - 1);
Activity_name object = ((Activity_name)v.getContext());
object.onResume();
setContentView(v);
}
else {
this.finish();
}
}
onResume is a lifecycle method called by OS when activity comes to the top of the stack. You can't call it directly.

Categories