如何根据API的改进响应验证手机号码?

时间:2018-05-10 08:41:45

标签: android asynchronous retrofit2

我在node.js中有后端api,并从中制作Android应用程序。在Android应用程序中有两个文本框和一个提交按钮。用户填写两个字段并单击提交后,我想验证移动是否已存在。我正在使用retrofit2进行api通话。现在问题是api调用需要一些时间来验证移动和使用异步调用进行改造下一个代码首先运行并且api响应稍后出现。我希望在api工作期间显示一个微调器。但我无法做到。因为我是android的新手,请帮助代码。

这是 RegisterActivity.java 文件:

package com.example.narmail.truck30mint;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.narmail.truck30mint.Api.services.UserApi;
import com.example.narmail.truck30mint.Api.services.NetworkStatus;

public class RegisterActivity extends AppCompatActivity {
    EditText registerMobileInput, registerPasswordInput;
    Button registerButton;
    ProgressBar progressBar;
    public static String existmsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        progressBar = findViewById(R.id.progressBar);
        registerMobileInput = findViewById(R.id.registerMobileInput);
        registerPasswordInput = findViewById(R.id.registerPasswordInput);
        registerButton = findViewById(R.id.registerButton);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkStatus.isOnline(getApplicationContext())) {
                    if (validate()) {
                        Intent data = new Intent(RegisterActivity.this, OtpActivity.class);
                        data.putExtra("mobile", registerMobileInput.getText().toString());
                        data.putExtra("pass", registerPasswordInput.getText().toString());
                        startActivity(data);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Please connect to internet", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public boolean validate() {
        if (registerMobileInput.getText().toString().trim().length() == 0) {
            Toast.makeText(getApplicationContext(), "mobile number is mandatory", Toast.LENGTH_LONG).show();
            return false;
        } else if (registerMobileInput.getText().toString().trim().length() > 0 && registerMobileInput.getText().toString().trim().length() != 10) {
            Toast.makeText(getApplicationContext(), "Enter correct mobile number", Toast.LENGTH_LONG).show();
            return false;
        } else if (registerMobileInput.getText().toString().trim().length() == 10) {
            UserApi.mobileExist(registerMobileInput.getText().toString());

            while (existmsg == null) {
                progressBar.setVisibility(View.VISIBLE);
                System.out.println("in while loop");
            }
            progressBar.setVisibility(View.GONE);
            System.out.println("just below method called");
            if (existmsg != null && existmsg.equalsIgnoreCase("exist")) {
                Toast.makeText(getApplicationContext(), "mobile number already exist please login", Toast.LENGTH_LONG).show();
                return false;
            } else if (existmsg != null && existmsg.equalsIgnoreCase("notExist")) {
                return true;
            } else {
                Toast.makeText(getApplicationContext(), "Some error occured plz try again", Toast.LENGTH_LONG).show();
                return false;
            }
        } else if (registerPasswordInput.getText().toString().trim().length() == 0) {
            Toast.makeText(getApplicationContext(), "Password is mandatory", Toast.LENGTH_LONG).show();
            return false;
        } else if (registerPasswordInput.getText().toString().trim().length() < 6) {
            Toast.makeText(getApplicationContext(), "Please enter Min 6 chars", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
}

这是java模型类

package com.example.narmail.truck30mint.Api.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class mobileExist {
    @SerializedName("status")
    @Expose
    private String status;

    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}

这是Api

package com.example.narmail.truck30mint.Api.services;

import android.util.Log;

import com.example.narmail.truck30mint.Api.interfaces.UserClient;
import com.example.narmail.truck30mint.Api.models.mobileExist;
import com.example.narmail.truck30mint.RegisterActivity;
import com.google.gson.GsonBuilder;

import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserApi {
    private static String mobile_exist_url = "http://10.0.2.2:3002/";
    private static Retrofit retrofit;
    private static UserClient apiInterface;
    private static String mobileNoStatus;
    private static String signupStatus;
    private static Retrofit getMobileExist(){
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(mobile_exist_url).callbackExecutor(Executors.newSingleThreadExecutor()).
                    addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
    /*activity method start*/
    public static void mobileExist(String mobile){
        apiInterface = UserApi.getMobileExist().create(UserClient.class);
        Call<mobileExist> call = apiInterface.getMobileExist(mobile);
        call.enqueue(new Callback<mobileExist>() {
            @Override
          public void onResponse(Call<mobileExist> call, Response<mobileExist> response) {
                if (response.isSuccessful()) {
                    System.out.println("response is successfull");
                    RegisterActivity.existmsg = response.body().getStatus();
                } else {
                    RegisterActivity.existmsg = "error";
                     Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
                }
                // Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
               // System.out.println("in response is now" + mobileNoStatus);
            }
                @Override
                public void onFailure (Call < mobileExist > call, Throwable t){
                    RegisterActivity.existmsg = "error";
                    Log.v("error", "is", t);
                }
        });
      // return false;
    }
}

这是布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout                                                               xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RegisterActivity">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:textSize="20sp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/pleaseRegister"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.386"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.128" />


    <EditText
        android:id="@+id/registerMobileInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="phone"
        android:hint="@string/mobileHintRegister"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.358" />

    <EditText
        android:id="@+id/registerPasswordInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="@string/passwordHintRegister"
        android:inputType="textPassword"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.503"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.498" />

    <Button
        android:id="@+id/registerButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="@string/register"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.453"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.653" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.459"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.223" />

</android.support.constraint.ConstraintLayout>

2 个答案:

答案 0 :(得分:0)

public static void mobileExist(String mobile, Context context){
    **Utility.showProgressDialog(context, "Please wait"); **
    apiInterface = UserApi.getMobileExist().create(UserClient.class);
    Call<mobileExist> call = apiInterface.getMobileExist(mobile);
    call.enqueue(new Callback<mobileExist>() {
        @Override
        public void onResponse(Call<mobileExist> call, Response<mobileExist> response) {
            if (response.isSuccessful()) {
                **Utility.dismissProgressDialog(); **
                System.out.println("response is successfull");
                RegisterActivity.existmsg = response.body().getStatus();
            } else {
                RegisterActivity.existmsg = "error";
                Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
            }
            // Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
            // System.out.println("in response is now" + mobileNoStatus);
        }
        @Override
        public void onFailure (Call < mobileExist > call, Throwable t){
            RegisterActivity.existmsg = "error";
            **Utility.dismissProgressDialog(); **
            Log.v("error", "is", t);
        }
    });
}

调用移动对话框后立即启动进度对话框,并在完成响应后关闭。

答案 1 :(得分:0)

我已修改了RegisterActivity和UserApi代码。您可以使用以下代码。 我添加了一个界面来处理您的移动验证回调

<强> RegisterActivity.java

   public class RegisterActivity extends AppCompatActivity implements ValidateMobile {
    EditText registerMobileInput, registerPasswordInput;
    Button registerButton;
    ProgressBar progressBar;
    public static String existmsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        progressBar = findViewById(R.id.progressBar);
        registerMobileInput = findViewById(R.id.registerMobileInput);
        registerPasswordInput = findViewById(R.id.registerPasswordInput);
        registerButton = findViewById(R.id.registerButton);

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkStatus.isOnline(getApplicationContext())) {
                    validate();
                } else {
                    Toast.makeText(getApplicationContext(), "Please connect to internet", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void validate() {
        if (registerMobileInput.getText().toString().trim().length() == 0) {
            Toast.makeText(getApplicationContext(), "mobile number is mandatory", Toast.LENGTH_LONG).show();
        } else if (registerMobileInput.getText().toString().trim().length() > 0 && registerMobileInput.getText().toString().trim().length() != 10) {
            Toast.makeText(getApplicationContext(), "Enter correct mobile number", Toast.LENGTH_LONG).show();
        } else if (registerMobileInput.getText().toString().trim().length() == 10) {
            UserApi.mobileExist(registerMobileInput.getText().toString());
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    public void startOtp() {
        Intent data = new Intent(RegisterActivity.this, OtpActivity.class);
        data.putExtra("mobile", registerMobileInput.getText().toString());
        data.putExtra("pass", registerPasswordInput.getText().toString());
        startActivity(data);
    }

    public void validateAndStartOtp() {
        if (registerPasswordInput.getText().toString().trim().length() == 0) {
            Toast.makeText(getApplicationContext(), "Password is mandatory", Toast.LENGTH_LONG).show();
        } else if (registerPasswordInput.getText().toString().trim().length() < 6) {
            Toast.makeText(getApplicationContext(), "Please enter Min 6 chars", Toast.LENGTH_LONG).show();
        } else {
            startOtp();
        }
    }

    @Override
    public void onMobileValidateSuccess() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onMobileValidateFailed() {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(getApplicationContext(), "mobile number already exist please login", Toast.LENGTH_LONG).show();
    }
}

<强> UserApi.java

import android.content.Context;
import android.util.Log;

import com.example.narmail.truck30mint.Api.interfaces.UserClient;
import com.example.narmail.truck30mint.Api.models.mobileExist;
import com.example.narmail.truck30mint.RegisterActivity;
import com.google.gson.GsonBuilder;

import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserApi {
    private static String mobile_exist_url = "http://10.0.2.2:3002/";
    private static Retrofit retrofit;
    private static UserClient apiInterface;
    private static String mobileNoStatus;
    private static String signupStatus;
    private static Retrofit getMobileExist(){
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(mobile_exist_url).callbackExecutor(Executors.newSingleThreadExecutor()).
                    addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
    /*activity method start*/
    public static void mobileExist(String mobile, Context mContext){

        // Interface callback
        final ValidateMobile callback = (ValidateMobile) mContext;

        apiInterface = UserApi.getMobileExist().create(UserClient.class);
        Call<mobileExist> call = apiInterface.getMobileExist(mobile);
        call.enqueue(new Callback<mobileExist>() {
            @Override
          public void onResponse(Call<mobileExist> call, Response<mobileExist> response) {
                if (response.isSuccessful()) {
                    // On success call this callback function   
                    callback.onMobileValidateSuccess();
                    System.out.println("response is successfull");
                } else {
                    // On failure call this callback function
                    callback.onMobileValidateFailed();
                    RegisterActivity.existmsg = "error";
                     Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
                }
                // Log.w("status ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
               // System.out.println("in response is now" + mobileNoStatus);
            }
                @Override
                public void onFailure (Call < mobileExist > call, Throwable t){
                    callback.onMobileValidateFailed();
                    RegisterActivity.existmsg = "error";
                    Log.v("error", "is", t);
                }
        });
      // return false;
    }
}

<强> ValidateMobile.java

public interface ValidateMobile {
    public void onMobileValidateSuccess();
    public void onMobileValidateFailed();
}