0

I'm working on an app where you can take multiple choice tests which it's main screen consist on a ViewPager and fragments where in each page of the viewpager one question of the test is displayed and the app is working quite well but there's something I'm not being able to achieve:

Questions and possible answers are loaded from sqlite internal app database and they have text formatted with some html and displayed with three webviews and sometimes specific pages take longer to fully render, and when I say "take longer" I'm not talking about milliseconds, maybe in certain occasions they may take up to two or three seconds to be fully rendered (very rare but happens) so I'd like to display a message in the form of "Loading Data..." so the users knows what it's going on.

I was able to create a nice blinking text TextView and I start showing it at the very beginning of "onCreateView" and disable it (with textView.setText("")) at the very end of the same "onCreateView" method which includes a drawPageN() method where all elements of a page are rendered but I'm not being able to make it to work, as the blinking "Loading Data..." appears but immediately dissapears not reflecting the real rendering time, sometimes page is still not fully rendered and message have already dissapeared.

I've tried other methods like "onViewCreated" to disabling the "loading text" message but no results either.

I thought on "onPreExecute" and "onPostExecute" but for this I have to do tasks in "doItOnBackgroung" and cannot update UI on a background thread.

OK, I think my goal "in concept" is simple but I need help on how to implement a working version, let's say, where to start the progress indicator and where to turn it off.

Thanks in advance.

Edit:

I have been trying Soba suggestion to use an AsyncTask with onPreExecute, doInBackground and onPostExecute but now it throws an error when trying to inflate the view, and it specifically points to the first WebView in XML, so I'm pasting some code and the error message in case it helps more.

    public static class TestSectionFragment extends Fragment { //static

        private static final String ARG_SECTION_NUMBER = "section_number";
        private WebView webViewInstructions, webViewQuestion;
        private LinearLayout ll, llTvQuestionInstructions;
        private int res;

        public TestSectionFragment() {
        }

        class asyncDrawPage extends AsyncTask<String, Integer, View> {

            LayoutInflater inflater;
            ViewGroup container;

            @Override
            protected View doInBackground(String... strConfig) {

                View rootView;
                Bundle arguments = getArguments();
                int pageNumber = arguments.getInt(ARG_SECTION_NUMBER);

                if (strTheme.equals(testMe.theme_vivid)) {
                    rootView = inflater.inflate(R.layout.activity_test_vivid, container, false);
                }else{
                    rootView = inflater.inflate(R.layout.activity_test, container, false);
                }

                String testName = test.getTestName();
                int testCategory = test.getIdCategory();
                int questionsCount = test.getQuestions().size();

                drawPageN(rootView, pageNumber, testCategory, testName, questionsCount, strTheme);

                return rootView;
            }
        }

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

            asyncDrawPage asyncDraw = new asyncDrawPage();
            asyncDraw.inflater = inflater;
            asyncDraw.container = container;

            View rootView = null;

            try {
                rootView = asyncDraw.execute().get();
            } catch (java.lang.InterruptedException e) {
                e.printStackTrace();
            } catch (java.util.concurrent.ExecutionException e) {
                e.printStackTrace();
            }

            return rootView;
        }
}

drawPageN is the method which fills all views (TextViews, WebViews, etc).

And the error message (which I had to cut as it is too long by the way):

01-23 10:09:33.133 24469-24469/com.testMe.testMe W/System.err: java.util.concurrent.ExecutionException: android.view.InflateException: Binary XML file line #74: Binary XML file line #74: Error inflating class android.webkit.WebView
01-23 10:09:33.134 24469-24529/com.testMe.testMe E/testMeLogging: [Error] UncaughtExceptionHandler threade = Thread[AsyncTask #3,5,main], error java.lang.RuntimeException: An error occurred while executing doInBackground()
01-23 10:09:33.135 24469-24469/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.report(FutureTask.java:94)
01-23 10:09:33.135 24469-24516/com.testMe.testMe W/System.err:     at java.lang.RuntimeException: An error occurred while executing doInBackground()
01-23 10:09:33.135 24469-24516/com.testMe.testMe W/System.err:     at android.os.AsyncTask$3.done(AsyncTask.java:309)
01-23 10:09:33.135 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
01-23 10:09:33.135 24469-24469/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:164)
01-23 10:09:33.135 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
01-23 10:09:33.135 24469-24469/com.testMe.testMe W/System.err:     at android.os.AsyncTask.get(AsyncTask.java:498)
01-23 10:09:33.135 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-23 10:09:33.136 24469-24469/com.testMe.testMe W/System.err:     at com.testMe.testMe.ActivityTest$TestSectionFragment.onCreateView(ActivityTest.java:1062)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at java.lang.Thread.run(Thread.java:818)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err: Caused by: android.view.InflateException: Binary XML file line #74: Binary XML file line #74: Error inflating class android.webkit.WebView
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at com.testMe.testMe.ActivityTest$TestSectionFragment$asyncDrawPage.doInBackground(ActivityTest.java:1009)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at com.testMe.testMe.ActivityTest$TestSectionFragment$asyncDrawPage.doInBackground(ActivityTest.java:996)
01-23 10:09:33.136 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
01-23 10:09:33.136 24469-24516/com.testMe.testMe W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-23 10:09:33.137 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
01-23 10:09:33.137 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
01-23 10:09:33.137 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
01-23 10:09:33.137 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643)
01-23 10:09:33.137 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
01-23 10:09:33.137 24469-24516/com.testMe.testMe W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-23 10:09:33.137 24469-24516/com.testMe.testMe W/System.err:  ... 4 more
01-23 10:09:33.138 24469-24469/com.testMe.testMe W/System.err: Caused by: android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
01-23 10:09:33.138 24469-24516/com.testMe.testMe W/System.err:  at android.view.InflateException: Binary XML file line #74: Error inflating class android.webkit.WebView
01-23 10:09:33.138 24469-24469/com.testMe.testMe W/System.err: android.support.v4.view.ViewPager.populate(ViewPager.java:1272)
01-23 10:09:33.138 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
01-23 10:09:33.139 24469-24469/com.testMe.testMe W/System.err:     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
01-23 10:09:33.139 24469-24469/com.testMe.testMe W/System.err:     at android.view.View.measure(View.java:18911)
01-23 10:09:33.139 24469-24469/com.testMe.testMe W/System.err:     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
01-23 10:09:33.139 24469-24469/com.testMe.testMe W/System.err:     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
01-23 10:09:33.140 24469-24469/com.testMe.testMe W/System.err:     at android.view.View.measure(View.java:18911)
01-23 10:09:33.140 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
01-23 10:09:33.141 24469-24469/com.testMe.testMe W/System.err:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
01-23 10:09:33.141 24469-24469/com.testMe.testMe W/System.err:     at android.view.View.measure(View.java:18911)
01-23 10:09:33.141 24469-24469/com.testMe.testMe W/System.err:     at android.widget.LinearLayout.measureVertical(LinearLayout.java:901)
01-23 10:09:33.141 24469-24469/com.testMe.testMe W/System.err:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
01-23 10:09:33.142 24469-24469/com.testMe.testMe W/System.err:     at android.view.View.measure(View.java:18911)
01-23 10:09:33.142 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5995)
01-23 10:09:33.142 24469-24469/com.testMe.testMe W/System.err:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
01-23 10:09:33.142 24469-24469/com.testMe.testMe W/System.err:     at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2662)
01-23 10:09:33.143 24469-24469/com.testMe.testMe W/System.err:     at android.view.View.measure(View.java:18911)
01-23 10:09:33.144 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2157)
01-23 10:09:33.146 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1261)
01-23 10:09:33.146 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1498)
01-23 10:09:33.146 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1140)
01-23 10:09:33.146 24469-24469/com.testMe.testMe W/System.err:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6232)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.view.Choreographer.doCallbacks(Choreographer.java:670)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.view.Choreographer.doFrame(Choreographer.java:606)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
01-23 10:09:33.147 24469-24469/com.testMe.testMe W/System.err:     at android.os.Looper.loop(Looper.java:148)
01-23 10:09:33.148 24469-24469/com.testMe.testMe W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5551)
01-23 10:09:33.148 24469-24469/com.testMe.testMe W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-23 10:09:33.148 24469-24469/com.testMe.testMe W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)...

Edit 3: As per suggestions more methods added.

@SuppressLint("SetJavaScriptEnabled")
public void drawPageN(View view, int pageNumber, int testCategory,
                      String testName, int questionsCount, String strTheme) {

    String htmlText;
    Context context = this.getActivity();

    tvFetchingData = (TextView) view.findViewById(R.id.llBody).findViewById(R.id.tvBlinking);
    tvFetchingData.setTextColor(Color.BLACK);
    tvFetchingData.setText("Loading data...");
    GeneralUtils.blinkText(tvFetchingData);

    if (test.getQuestions() != null) {

        Question question = test.getQuestions().get(pageNumber);

        if (question.getInstructions()!=null){
            webViewInstructions = (WebView) view.findViewById(R.id.llBody)
                    .findViewById(R.id.llTvQuestionInstructions)
                    .findViewById(R.id.webViewInstructions);

            llTvQuestionInstructions = (LinearLayout) view.findViewById(R.id.llBody)
                    .findViewById(R.id.llTvQuestionInstructions);

            //webViewInstructions.setWebViewClient(new WebViewClient());
            //webViewInstructions.setWebViewClient(new MYWEBCLIENT());
            webViewInstructions.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }
                @Override
                public void onPageFinished(WebView view, String url) {
                    if (webViewQuestion.getVisibility() != View.VISIBLE) {
                        webViewQuestion.setVisibility(View.VISIBLE);
                    }
                }
            });
            webViewInstructions.getSettings().setJavaScriptEnabled(true);
            webViewInstructions.getSettings().setDomStorageEnabled(true);
            webViewInstructions.setLayerType(View.LAYER_TYPE_NONE, null);
            webViewInstructions.setBackgroundColor(Color.argb(1, 0, 0, 0));
            //remove copy text
            webViewInstructions.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });
            webViewInstructions.setLongClickable(false);
            webViewInstructions.setTag(true);
            TestUtils.setZoom(webViewInstructions, null, context);

            htmlText = getHtmlText(question.getInstructions());
            webViewInstructions.loadDataWithBaseURL("", htmlText, "text/html", "UTF-8", "");
        } else {
            llTvQuestionInstructions.setVisibility(View.GONE);
        }

        webViewQuestion = (WebView) view.findViewById(R.id.llBody)
                .findViewById(R.id.llTvQuestion)
                .findViewById(R.id.webViewQuestion);

        //webViewQuestion.setWebViewClient(new WebViewClient());
        //webViewQuestion.setWebViewClient(new MYWEBCLIENT());
        webViewQuestion.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                if (webViewQuestion.getVisibility() != View.VISIBLE) {
                    webViewQuestion.setVisibility(View.VISIBLE);
                    tvFetchingData.setText("Data loaded...");
                }
            }
        });
        webViewQuestion.getSettings().setJavaScriptEnabled(true);
        webViewQuestion.getSettings().setDomStorageEnabled(true);
        webViewQuestion.setBackgroundColor(Color.argb(1, 0, 0, 0));
        //remove copy text
        webViewQuestion.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        webViewQuestion.setLongClickable(false);
        TestUtils.setZoom(webViewQuestion, null, context);

        //set webview text
        htmlText = getHtmlText(question.getQuestion());
        webViewQuestion.loadDataWithBaseURL("", htmlText, "text/html", "UTF-8", "");

        //ANSWERS

        generatePossibleAnswersCheckBoxes(test.getQuestions().get(pageNumber), view, pageNumber);

        // get the image name according to category, test number and
        // question number
        // example: c1-t1-q15.png
        // String imageName = "c" + String.valueOf(testCategory) + "t"
        // + testName + "q" + String.valueOf(pageNumber + 1);

        String imageName = question.getImage();
        if (imageName!=null) {
            res = getResources().getIdentifier(question.getImage(), "drawable",
                    context.getPackageName());
            if (res != 0) {
                //set the red text indicating there is an image below
                TextView tvImgInstructions = (TextView) view.findViewById(R.id.llBody)
                        .findViewById(R.id.llTvImgInstructions)
                        .findViewById(R.id.tvImgInstructions);

                ApplicationConfiguration testMe = new ApplicationConfiguration();
                String imageInstructionsTextColor = testMe.imageInstructionsTextColor;

                tvImgInstructions.setTextColor(Color.parseColor(imageInstructionsTextColor));
                tvImgInstructions.setText(GeneralUtils.getStringResourceByName(
                        "textview_activitytest_imginstructions", context));
                TestUtils.setZoom(null, tvImgInstructions, context);

                //get dimensions of question image
                Drawable d = getResources().getDrawable(res);
                int w = d.getIntrinsicWidth();
                int h = d.getIntrinsicHeight();
                //set img width and heigth to 90% of screen size to fit in screen
                int screenWidth = GeneralUtils.getScreenWidth(context);
                int imgWidth = (int)(screenWidth * 0.98);
                int wScaleFactor = imgWidth*100/w;
                int imgHeigth = h*wScaleFactor/100;

                ImageView imgQuestion = new ImageView(context);
                imgQuestion.setPadding(0, 50, 0, 0);
                imgQuestion.setId(R.id.imgQuestionX);
                imgQuestion.setTag(imageName);
                LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(imgWidth, imgHeigth);
                imgQuestion.setLayoutParams(parms);

                //set a border for the image
                imgQuestion.setAdjustViewBounds(true);
                imgQuestion.setScaleType(ScaleType.CENTER_INSIDE);
                imgQuestion.setBackgroundColor(Color.BLACK);
                imgQuestion.setPadding(1,1,1,1);
                imgQuestion.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

                imgQuestion.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        Context context = v.getContext();
                        String imgTag = (String) v.getTag();
                        Bundle bImageData = new Bundle();
                        bImageData.putString("imgTag", imgTag);
                        bImageData.putString("testName", test.getTestName());
                        Intent intent = new Intent(
                                context,
                                ActivityImgFullScreen.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        intent.putExtras(bImageData);
                        startActivity(intent);
                    }
                });
                ll = ((LinearLayout) view.findViewById(R.id.llQuestionImage));
                ll.addView(imgQuestion);
                imgQuestion.setImageResource(res);
            } else {
                //for now used in literature for poems and additional text
                //TODO: make a special field for text
                TextView tvAdditionalText = new TextView(context);
                String additionalText = question.getImage();
                tvAdditionalText.setTextColor(Color.BLACK);
                int screenWidth = GeneralUtils.getScreenWidth(context);
                int screenHeight = GeneralUtils.getScreenHeight(context);
                float textSize = GeneralUtils.getTextSize(additionalText, screenWidth, screenHeight) * 3;
                tvAdditionalText.setTextSize(textSize);
                tvAdditionalText.setText(additionalText);
                ll = ((LinearLayout) view.findViewById(R.id.llQuestionImage));
                ll.addView(tvAdditionalText);
            }
        }
    }

    if (webViewInstructions.getTag().equals(true)){
        webViewInstructions.setPadding(0, 0, 0, 0);
    }

    //add extra space so question image can be scrolled up and seen completely
    //the space added is double the end test linear layout height
    int llHeight=0;
    if (img != null) {
        llHeight = (img.getIntrinsicHeight()); // the heigth of the end test image
    }

    LinearLayout llSpacer = new LinearLayout(context);
    LinearLayout.LayoutParams parmsSpacer = new LinearLayout.LayoutParams(llHeight, llHeight);
    llSpacer.setLayoutParams(parmsSpacer);
    ll.addView(llSpacer);

    String strQuestion = GeneralUtils.getStringResourceByName("activitytest_labelview_question", context);

    String pagerTextNoArrows=strQuestion + " "
            + Integer.toString(pageNumber + 1) + " / "
            + questionsCount;

    if (strTheme.equals(testMe.theme_vivid)) {
        TextView tvQuestionNumber = (TextView) view.findViewById(R.id.tvQuestionNumber);
        tvQuestionNumber.setText(pagerTextNoArrows);
    }else{
        String pagerText = "↑   " + pagerTextNoArrows + "   ↓";

        VerticalLabelView vertical;
        int defFontSize = GeneralUtils.getPrefsByScreenDensity(this.getActivity())[5];
        ll = ((LinearLayout) view.findViewById(R.id.llVerticalPager));
        int paddingLeft = GeneralUtils.dp2px(5, context);
        int paddingBottom = GeneralUtils.dp2px(100, context);
        ll.setPadding(paddingLeft, 0, 0, paddingBottom);
        if (strTheme.equals(testMe.theme_blue)){
            ll.setBackgroundColor(Color.parseColor(testMe.btnStartColor_blue));
        }

        vertical = new VerticalLabelView(context);
        vertical.setTextColor(Color.WHITE);
        vertical.setText(pagerText);
        vertical.setTextSize(GeneralUtils.dp2px(defFontSize, this.getActivity()));

        ll.addView(vertical);
    }
}

@SuppressLint("SetJavaScriptEnabled")
private void generatePossibleAnswersCheckBoxes(final Question question,
                                               View view, final int pageNumber) {

    Context context = view.getContext();
    String htmlText="";
    int i = 0;
    final List<Answer> answers = question.getAnswers();
    nroAnswers = answers.size();

    if (ll != null) {
        ll.removeAllViews();
    }
    if (answers != null) {
        for (Answer rbAnswer : answers) {
            int cbIndex = answers.size()*pageNumber+i;
            // linear layout to hold image checkbox and checkbox text
            LinearLayout llCheckBox = new LinearLayout(context);
            llCheckBox.setOrientation(LinearLayout.HORIZONTAL); // horizontal
            llCheckBox.setGravity(Gravity.CENTER_VERTICAL);
            llCheckBox.setPadding(0, 0, 0, 5);
            //webview for answer
            final WebView webView = new WebView(context);
            webView.setVisibility(View.INVISIBLE);
            //webView.setWebViewClient(new WebViewClient());
            //webView.setWebViewClient(new MYWEBCLIENT());
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    return false;
                }
                @Override
                public void onPageFinished(WebView view, String url) {
                    if (webView.getVisibility() != View.VISIBLE) {
                        webView.setVisibility(View.VISIBLE);
                    }
                }
            });
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setDomStorageEnabled(true);
            webView.setBackgroundColor(Color.argb(1, 0, 0, 0));
            webView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return true;
                }
            });
            webView.setLongClickable(false);

            htmlText = getHtmlText(rbAnswer.getAnswer());
            webView.loadDataWithBaseURL("", htmlText, "text/html", "UTF-8", "");
            TestUtils.setZoom(webView, null, context);

            // checkbox i
            cbAnswer[cbIndex] = new ImageView(context);
            cbAnswer[cbIndex].setTag("0@" + rbAnswer.getIdAnswer()+ "@" + pageNumber); // 0=>unchecked|1=>checked
            cbAnswer[cbIndex].setId(cbIndex);

            // determine if checkbox is checked or not according to what
            // is stored in array of already answered questions
            int answeredInCurrentPage = test.getAnsweredQuestions().get(pageNumber).getIdAnswer();
            if (rbAnswer.getIdAnswer() == answeredInCurrentPage) {
                if (voicerecognitionPreference){
                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_checked_say);
                }else{
                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_checked);
                }
            } else {
                if (voicerecognitionPreference){
                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked_say);
                }else{
                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked);
                }
            }

            int cbPadBottom = 5;
            int cbPadTop = 5;
            int cbPadRight = 15;
            int cbPadLeft = 0;
            cbAnswer[cbIndex].setPadding(cbPadLeft, cbPadTop, cbPadRight, cbPadBottom);

            // add elements to linear layout
            // create and add textview with "tooltip" say nro.
            if (voicerecognitionPreference){
                addTextViewSay(llCheckBox, i+1);
            }

            llCheckBox.addView(cbAnswer[cbIndex]);
            llCheckBox.addView(webView);

            cbAnswer[cbIndex].setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Context context = v.getContext();

                    //play click sound
                    SoundManager.playSound(context, testMe.getDefaultCheckBoxClickSound(), testMe.getSoundType()[0]);
                    ImageView cbSelected = (ImageView) v;

                    //String strRest = cbSelected.getTag().toString().substring(1);
                    //cbAnswer[cbIndex].setTag("1"+strRest);

                    int cbSelectedId = cbSelected.getId();
                    int cbSelectedTagId = Integer.parseInt(cbSelected.getTag().toString().split("@")[1]);
                    for (int j = 0; j < answers.size(); j++) {
                        int cbIndex = answers.size()*pageNumber+j;
                        boolean isSelected = cbAnswer[j].getTag().toString().substring(0, 1).equals("1");
                        if (cbIndex != cbSelectedId) {
                            // (cbAnswer[j].get
                            // .isChecked()==true &&
                            // j!=cbSelectedId)
                            if (voicerecognitionPreference){
                                cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked_say);
                            }else{
                                cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked);
                            }
                            String strRest = cbAnswer[cbIndex].getTag().toString().substring(1);
                            cbAnswer[cbIndex].setTag("0"+strRest);
                        } else {
                            String cbAnswerJTag = cbAnswer[cbIndex].getTag().toString();
                            String cbAnswerJState = cbAnswerJTag.split("@")[0];

                            if (cbAnswerJState.equals("1")) { // 0=>unchecked|1=>checked
                                if (voicerecognitionPreference){
                                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked_say);
                                }else{
                                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_unchecked);
                                }
                                cbAnswer[cbIndex].setTag("0@" + cbAnswerJTag.split("@")[1]);
                            } else {
                                if (voicerecognitionPreference){
                                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_checked_say);
                                }else{
                                    cbAnswer[cbIndex].setImageResource(R.drawable.checkbox_checked);
                                }
                                cbAnswer[cbIndex].setTag("1@" + cbAnswerJTag.split("@")[1]);
                            }
                        }
                    }
                    test.getAnsweredQuestions().get(pageNumber).setIdAnswer(cbSelectedTagId);
                    test.getAnsweredQuestions().get(pageNumber).setIdQuestion(question.getIdQuestion());
                }
            });
            ll = ((LinearLayout) view.findViewById(R.id.cbLayout));
            ll.addView(llCheckBox);
            i++;
        }
    }
}
Diego Perez
  • 2,188
  • 2
  • 30
  • 58
  • This is happen because, ViewPager loads first three screens in always. Eg, Left side screen <> Your screen <> Right side screen. So you can check your code should work by commenting other async tasks (left and right). – Charitha Ratnayake Jan 23 '17 at 09:43
  • Thank you very much for your answer Charitha, I've been checking and I don't have any other async tasks running in this screen so not sure if this could be the problem. – Diego Perez Jan 23 '17 at 11:49
  • As additional information on each of the fragment's pages when drawing each page I'm not doing any special (or important, time consuming or network) calculation just reading data from an array previously generated which reads data from sqlite, the problem is although this some pages of the view pager (occurs randomly) takes more time to fully render webviews contents so that's why I'd like to show the user some sort of message. – Diego Perez Jan 23 '17 at 12:00
  • drawPageN() please add this method also. – Charitha Ratnayake Jan 23 '17 at 12:14
  • Thanks for your efforts Charitha I appreciate it a lot, drawPageN and generateCheckboxers methods aded. – Diego Perez Jan 23 '17 at 14:18
  • OK, this is the thing in `drawPageN()` has bunch of UI implementations Eg. `ll.addView(llSpacer)`, `tvFetchingData.setText("Loading data...")`. Those UI cannot access by background thread. That means you cant `setText()` in `doInBackground()` method. So I'll add an answer to show the implement should be... – Charitha Ratnayake Jan 24 '17 at 05:06

3 Answers3

0

Actually, AsyncTask's onPreExecute() and onPostExecute methods are invoked on the UI thread so it's perfectly safe to show and dismiss your progress bars (or in your case, blinking textviews) there.

@Override
protected void onPreExecute() {
   //Show progressbar
}

@Override
protected Void doInBackground(Void... params) {
   //Fetch data
}

@Override
protected void onPostExecute(Void aVoid) {
   //Dismiss progressbar
    }
SobaDeveloper
  • 1,197
  • 10
  • 7
  • Thank you very much Soba, I have been trying your suggestion but unlickily it didn't work, it throws an error when trying to inflate the view (and curiously it points to the the first webview in the xml file, which is below some edittext) and so view returns null and screen is displayed in black. I will edit my post so to add the error message and some code so you can help me further. All the best! – Diego Perez Jan 23 '17 at 09:18
0

Use onProgressUpdate and publishProgress methods of AsyncTask for this:

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

Refer This Answer

Community
  • 1
  • 1
Amrut Bidri
  • 6,276
  • 6
  • 38
  • 80
  • Thank you very much for your quick response Amrut, I appreciated a lot and didn't know about those two methods. I'd love to give a try but if you read my complete post the problem I'm having is I'm not being able to update fragment UI in doInBackground method, it throws an error when trying to inflate the view, and specifically points to the first webview. Do you have any idea on what can be wrong? – Diego Perez Jan 23 '17 at 09:43
  • to avoid those errors you should use these publish methods. whenever u want to update your UI from async task doinbackground method, call the publishProgress method. It will ultimate call the onProgressUpdate method on Ui thread, so can u perform any UI operations in that method – Amrut Bidri Jan 23 '17 at 09:49
  • Hello Amrut, to start from a beginning I'm firts trying to execute my drawPage of the fragment method in an async task (forgetting of the "Loading..." message) and once it's working I focus on the progress, but the fact is I'm not even being able to run drawPageN in doInBackground as it throws the above error saying it cannot inflate the view. – Diego Perez Jan 23 '17 at 11:53
  • OK Amrut, thanks for your help, I'm almost giving up then, as I'm not being able to find a solution with my schema. – Diego Perez Jan 23 '17 at 15:37
0

As I have finally found a solution I decided to answer my own question in case it is useful to anyone else.

After a big optimization of the drawPageN method (which as name suggests renders ev'ry page of my view pager) what I was able to do with success is the next:

First I reorganized code so the three webviews will now load in order using onPageFinished on each one, then in onCreateView of the SectionFragment I set "Loading Data..." blinking text TextView to on and in the last WebView onPageFinished I set TextView text to empty.

I have already tried this before with no success but the key now was to achieve that WebViews load in order using onPageFinished.

I hope it helps anyone else, and thanks for all your efforts.

Diego Perez
  • 2,188
  • 2
  • 30
  • 58