0

This piece of code is called twice, when fragment is visible to user, triggering a double request to the backend server, not know why. I would evitate to use as workaround a counter, stopping process on the second time.Somebody know how to trigger it once for time, when navigating?

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


        if(isVisible()){

            //Toast.makeText(getContext(), ((ActivityLogin) getActivity()).choiceButton, Toast.LENGTH_LONG).show();

            counter++;
            //if(counter > 1 ) return;


            String ex = extractUni(getContext());

            //CERCA I DATI
            SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
            String username = preferences.getString("username", "");
            String password = preferences.getString("password", "");

            // PRENDI I DATI
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));


            String ch = ((ActivityLogin) getActivity()).choiceButton;

            if (ch.equals("login")) {

                //LOGIN
                try {
                    Toast.makeText(getContext(), "counter"+counter, Toast.LENGTH_LONG).show();
                    URL address = new URL("https://api.xxx.it/" + ex + "/login/");
                    Toast.makeText(getContext(), address+" >> login",+Toast.LENGTH_SHORT).show();
                    URLDataReader pp = new URLDataReader(getContext(), this, nameValuePairs);
                    pp.execute(address);


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

            } else {
              Toast.makeText(getContext(), "counter"+counter, Toast.LENGTH_LONG).show();
                try {

                    URL address = new URL("https://api.xxx.it/" + ex + "/ping/");
                    Toast.makeText(getContext(), address+" >> ping",+Toast.LENGTH_SHORT).show();
                    URLDataReader pp = new URLDataReader(getContext(), this, nameValuePairs);
                    pp.execute(address);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

            }

        }
    }

1 Answers1

0

Just changing isVisible() to isVisibleToUser

AskNilesh
  • 67,701
  • 16
  • 123
  • 163