Android Studio, Volley, api ответ не отображается при первом нажатии - PullRequest
0 голосов
/ 29 октября 2018

Это простой проект, я получаю данные json (в виде строки) из https://jsonplaceholder.typicode.com/todos/1, используя Volley

  1. Я разделил Activity, Logic (используя Presenter) и Service (которые будут общаться с оставшейся службой, используя POST, GET и т. Д.)

  2. Теперь в упражнении есть кнопка входа в систему и прослушиватель щелчков (ее реализация находится в WelcomePresenter)

  3. Когда пользователь вводит электронную почту и пароль, (не путайте себя с электронной почтой, это просто будущая функция) Я объединяю строку "https://jsonplaceholder.typicode.com/todos/" + userpassword в классе обслуживания и выполняю метод GET .

  4. Если HTTP-код состояния ответа равен 200, я открываю новое действие, которое напечатает справедливый ответ, в противном случае останется тем же действием и выдаст тост-сообщение «Заполните области»

  5. Вот что получается;

    • Когда я нажимаю кнопку «Войти» (я ввел пароль как 100, поэтому я использую метод GET https://jsonplaceholder.typicode.com/todos/100)
    • Однако при первом щелчке появляется сообщение Toast, после многих щелчков открывается новое действие)

Вот WelcomeView

public class WelcomeActivity extends AppCompatActivity implements WelcomeView {
    private WelcomePresenter welcomeBasePresenter;
    private EditText usermail, userpassword;
    private Button loginButton;
    private RequestQueue requestQueue;
    private Service restService;
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_welcome);

         this.usermail = findViewById(R.id.welcome_activity_edittext_username);
         this.userpassword = findViewById(R.id.welcome_activity_edittext_userpassword);
         this.loginButton = findViewById(R.id.welcome_activity_button_login);
         this.requestQueue = VolleySingleton.getInstance(this).getRequestQueue();
         this.restService = new ServiceImpl(this.requestQueue);

         this.welcomeBasePresenter = new WelcomePresenterImpl(this, this.restService);

         this.loginButton.setOnClickListener((v) -> {
         String usermail = this.usermail.getText().toString();
         String password = this.userpassword.getText().toString();
         this.welcomeBasePresenter.loginButtonListener(usermail, password);
         });
    }
    public void loadErrorMessage(String... errorMessage) {
      //make toast message
    }
    public void loadUserPageActivity() {
       // load new activity
    }
}

Вот WelcomePresenter

public class WelcomePresenterImpl implements WelcomePresenter {
    private WelcomeView welcomeView;
    private Service service;

    public WelcomePresenterImpl(WelcomeView responsibleView, Service restServis){
        this.welcomeView = responsibleView;

        this.service = restServis;
    }

    public void loginButtonListener(String usermail, String userpassword) {
        service.validateUser(usermail, userpassword);
        if (service.getUserRegisterHttpCode() == 200){
        this.welcomeView.loadUserPageActivity(service.getJsonData());
        }else{
            this.welcomeView.loadErrorMessage();
        }
    }
}

Вот класс Service, который общается с бэкэндом

public class ServiceImpl implements Service{
    private String jsonData;
    private RequestQueue requestQueue;
    private int userRegisterHttpCode;

    public ServiceImpl(RequestQueue requestQueue){
        this.requestQueue = requestQueue;
    }

    public void validateUser(String usermail, String userpassword){
        String url = EndPoint.URL.getUrl() + userpassword;
        StringRequest stringRequest = new StringRequest(
               Request.Method.GET, 
               url, 
               response -> userToken = response, 
               error -> setUserRegisterHttpCode(error.networkResponse.statusCode)){
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            setUserRegisterHttpCode(response.statusCode);

            return super.parseNetworkResponse(response);

        };
        this.requestQueue.add(stringRequest);
    }
}
...