12

I have a fragment which shows a line chart created with MPAndroidChart. Loading the fragment takes about 200 milliseconds.

I want to improve the perceived app performance by loading the chart data data right after the fragment becomes visible.

Therefore I need to execute code right after the fragment becomes visible, but only the FIRST time it becomes visible.

I can not use onResume(), since it gets called just before the fragment is visible.

Note: I can not use an asynchrounous task, it needs to be done on the UI-thread.

7
  • Are you saying you can't put the code in the Fragment's onResume or the Activity's onResume? Sep 3, 2015 at 14:41
  • Currently the code is in the fragment's onCreateView(). I can not use onResume() anyway, neither the activity, nor the fragment's onResume().
    – Mike76
    Sep 3, 2015 at 14:45
  • I'm not sure I'm understanding why you can't use the Fragment's onResume. That method gets called after the Fragment becomes visible. Sep 3, 2015 at 14:47
  • He wants it to execute the first time. onCreateView is the way to go Sep 3, 2015 at 14:48
  • Yes but you could always create a flag that the indicates the code has already run. Sep 3, 2015 at 14:49

5 Answers 5

7
public class MyFragment extends Fragment{
  Boolean _areLecturesLoaded =false;
  @Override
  onCreateView(){
    //Inflate the required views. Code gets executed once View is made but not shown
    return v;
}
@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //Code executes EVERY TIME user views the fragment

        if (isVisibleToUser && !_areLecturesLoaded ) {
            _areLecturesLoaded = true;
            // Code executes ONLY THE FIRST TIME fragment is viewed.
        }
    }
}

isVisisbleToUser is inbuilt and it is true when the user is viewing the current fragment. Until the user sees the fragment for the first time it will remain false. If you want some code to execute everytime the user views the fragment place the code in this area but outside the if statement.

_areLecturesLoaded is initialized as false and once the fragment for the first time, it is set to true ensuring the If statement will not be called in the future and the code within is executed ONLY ONCE

All initializing of views widgets buttons etc. must be done in the onCreate() to ensure no possibility of null pointer and other such pesky exceptions.

8
  • Thank you I will give it a try.
    – Mike76
    Sep 3, 2015 at 15:06
  • let me know if you face any issues. Else do accept the answer. Thanks Sep 3, 2015 at 15:41
  • Unfortunately setUserVisibleHint never receives a call. I tested it with logs on android 4.4. Maybe it works only if I would use a viewpager or something.
    – Mike76
    Sep 4, 2015 at 6:44
  • What are you attaching the fragment to? It depends on that. Im currently using fragments with a viewpager. Sep 4, 2015 at 6:47
  • 1
    I just use the fragment manager to load it and put it on the backstack. I read from other sources that the viewpager calls setUserVisibleHint whenever a viewpager-fragment becomes visible. But it seems not to be called in the default fragment lifecycle...
    – Mike76
    Sep 4, 2015 at 17:24
1

Doing anything lengthy on the UI thread is bad practice -- you'll block the whole UI for the length of your processing (since there's only one UI thread). And 200ms is actually very long, it's 1/5th of a second, easily detectable by human eye, imagine you're playing a game at a framerate of 5fps.

Perceived performance is all about never having UI lags.

Use either AsyncTask or AsyncTaskLoader to process your data, callbacks will be called on the UI thread, so no worries there. You can control whether it's one-time or not by storing the data in, say, a member variable. If it's null -- load, if not -- use right away.

If your data is fairly static and not very large -- pre-load it before your fragment is opened (say, when Activity starts, or even when the app starts) and just pass the data to the fragment when isntantiating (via a Bundle argument).

4
  • I can not use AsyncTask since I need to initalize my chart on the UI thread. 200 milliseconds is long, but the user can not do anything without this chart. Therefore I can only show a progress bar for the 200 milliseconds.
    – Mike76
    Sep 3, 2015 at 15:10
  • your progress bar will be frozen if you take 200ms of the UI thread time. Why do you need it to be processed on the UI thread? Sep 3, 2015 at 15:13
  • This is true, but the processing is all about updating the chart UI.
    – Mike76
    Sep 3, 2015 at 15:20
  • Hm, ok I may not see the whole picture then :) Now I'm kinda curious to see some code that shows what you're doing. Sep 3, 2015 at 15:24
1

It can be implemented by using a static boolean variable. I used the code below to show the progress dialog only on the first time the app is launched.

public class SettingsFragment extends Fragment {

    static boolean _areLecturesLoaded = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_settings, container, false);

        return rootView;
    }

    private class Getlimits extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = ProgressDialog.show(getActivity(), "", "Loading...", true);
            pd.setCancelable(false);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            //your background code
            if(_areLecturesLoaded) {
                try {
                    Thread.sleep(3500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pd.isShowing())
                pd.dismiss();
            _areLecturesLoaded = false;
        }
    }
}
1

define and override

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

}

then put in onCreateView() function these two lines

      setUserVisibleHint(false);
      setUserVisibleHint(true);

then put the code you wanted to be done at fragment start in onStart() function

@Override
public void onStart() {
    super.onStart();
     //your initial code is here.
}
0

Put it in the onViewCreated() method.

1
  • 2
    Seems to be the wrong thing. It is called even before onResume(). ->...... "Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. The fragment's view hierarchy is not however attached to its parent at this point."
    – Mike76
    Sep 3, 2015 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.