setUserVisibleHint两次崩溃

时间:2018-05-19 06:55:45

标签: android android-asynctask setuservisiblehint

这段代码被调用两次,当片段对用户可见时,触发对后端服务器的双重请求,不知道原因。我会假装使用计数器作为解决方法,第二次停止进程。有人知道如何在导航时一次触发它吗?

@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 个答案:

答案 0 :(得分:0)

只需将isVisible()更改为isVisibleToUser

即可