API user authentication using retrofit










0















I'm learning REST using Retrofit to register and login on an API in swaggerhub but i'm unable to do it, and it is not showing any error message in my studio. I have google REST AUTHENTICATRION but non of the link was helpful. I have also looked here and here but still couldn't figure it out.



HERE IS MY SignUpActivity



public class SignUpActivity extends AppCompatActivity implements View.OnClickListener 
private EditText mPassword;
private EditText mPassword2;
private String password;


private CountryCodePicker ccp;

private ProgressDialog pDialog;
private ProgressBar progressBar;


LoginServices loginService;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_activity);




findViewById(R.id.sign_up_button).setOnClickListener(this);

mPassword = findViewById(R.id.password);
mPassword2 = findViewById(R.id.password2);

progressBar = findViewById(R.id.login_progress);

loginService = ServiceGenerator.createService(LoginServices.class,
getApplication(), USER_BASE_URL);


ccp = findViewById(R.id.ccp);
EditText mUsername = findViewById(R.id.username);
ccp.registerCarrierNumberEditText(mUsername);




private boolean validateForm()

boolean valid = true;
View focusView = null;

password = mPassword.getText().toString();
// String conPassword = mConfirmPasswordView.getText().toString();
if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
mPassword.setError(getString(R.string.error_invalid_password));
focusView = mPassword;
valid = false;
else
mPassword.setError(null);


if (!valid)
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();

return valid;


private boolean isPasswordValid(String password)
String password2 = mPassword2.getText().toString();
// Add regex for at least 8 characters including lower case, upper case, digit and special character
return password.equals(password2) && password.length() >= 6;



private void submitUserDetails( String email, String password)

startUi();

Call<Message> call = loginService.createUser(email, password);

call.enqueue(new Callback<Message>()
@Override
public void onResponse(Call<Message> call, Response<Message> response)
if (response.isSuccessful())
// hidepDialog();
stopUi();
if (response.body() != null)
Message message = response.body();
String regMessage = message.getEmail();
Log.d("GET INFORMATION: ", call.toString());
Log.d("GET MESSAGE: ", message.toString());

Toast.makeText(getApplicationContext(), regMessage + "registered successfully", Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
finish();


else
// hidepDialog();
stopUi();
Toast.makeText(getApplicationContext(), "error signup user", Toast.LENGTH_SHORT)
.show();



@Override
public void onFailure(Call<Message> call, Throwable t)

stopUi();
Toast.makeText(getApplicationContext(), "error registering user "
+ t.getMessage(), Toast.LENGTH_SHORT)
.show();

);





private void startUi()
progressBar.setVisibility(View.VISIBLE);

private void stopUi()
progressBar.setVisibility(View.INVISIBLE);


@Override
public void onClick(View view)
int id = view.getId();
if (id == R.id.sign_up_button)
if (validateForm())
submitUserDetails(ccp.getDefaultCountryCodeWithPlus(), password);





LoginServices



public interface LoginServices 

@FormUrlEncoded
@POST(Routes.CREATE_USER)
Call<Message> createUser(@Field("email") String email, @Field("password") String password);

@FormUrlEncoded
@POST(Routes.USER_LOGIN)
Call<LoginUser> userLogin(@Field("email") String email, @Field("password") String password);




LoginActivity



public class LoginActivity extends AppCompatActivity implements View.OnClickListener 

private ProgressDialog pDialog;
private ProgressBar progressBar;

private EditText mEtUsername, mEtPassword;
private String username, password;

LoginServices loginService;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);


progressBar = findViewById(R.id.login_progress);

mEtUsername = findViewById(R.id.et_login_username);
mEtPassword = findViewById(R.id.et_login_password);

findViewById(R.id.btn_login).setOnClickListener(this);
findViewById(R.id.btn_login_register).setOnClickListener(this);

loginService = ServiceGenerator.createService(LoginServices.class, getApplication(), USER_BASE_URL);



private boolean validateForm()

boolean valid = true;
View focusView = null;

username = mEtUsername.getText().toString();
password = mEtPassword.getText().toString();
if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
mEtPassword.setError(getString(R.string.error_invalid_password));
focusView = mEtPassword;
valid = false;
else
mEtPassword.setError(null);


// Check for a valid phone number

if (TextUtils.isEmpty(username))
mEtUsername.setError("phone number is empty");
focusView = mEtUsername;
valid = false;
else
mEtUsername.setError(null);

if (!valid)
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();

return valid;


private boolean isPasswordValid(String password)
// Add regex for at least 8 characters including lower case, upper case, digit and special character
return password.length() >= 6;


private void login(String email, final String password)

startUi();

Call<LoginUser> call = loginService.userLogin(email, password);

call.enqueue(new Callback<LoginUser>()
@Override
public void onResponse(Call<LoginUser> call, Response<LoginUser> response)
if (response.isSuccessful())

stopUi();

if (response.body() != null)
LoginUser message = response.body();

String email = message.getEmail();
String password1 = message.getPassword();

if (password.equals(password1))
PrefManager.saveEmail(email, getApplicationContext());
PrefManager.saveUsername(username, getApplicationContext());

Toast.makeText(getApplicationContext(), "user authenticated successfully "
+ email, Toast.LENGTH_SHORT)
.show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
else
Toast.makeText(getApplicationContext(), "Invalid username or password "
+ email, Toast.LENGTH_SHORT)
.show();



else

stopUi();

Toast.makeText(getApplicationContext(), "error login user", Toast.LENGTH_SHORT)
.show();



@Override
public void onFailure(Call<LoginUser> call, Throwable t)

stopUi();

Toast.makeText(getApplicationContext(), "error registering user " + t.getMessage(), Toast.LENGTH_SHORT)
.show();

);


@Override
public void onClick(View view)

switch (view.getId())
case R.id.btn_login:
if (validateForm())
login(username, password);

break;
case R.id.btn_login_register:
startActivity(new Intent(LoginActivity.this,
SignUpActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;


private void startUi()
progressBar.setVisibility(View.VISIBLE);

private void stopUi()
progressBar.setVisibility(View.INVISIBLE);





ServiceGenerator



public class ServiceGenerator 
public static <S> S createService(Class<S> serviceClass, Context context, String baseUrl)
baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
String token = "";
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setPrettyPrinting()
.setVersion(1.0)
.create();

Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(baseUrl);

OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.readTimeout(90, TimeUnit.SECONDS)
.connectTimeout(90, TimeUnit.SECONDS)
.writeTimeout(90, TimeUnit.SECONDS)
.cache(null);

if (BuildConfig.DEBUG)
HttpLoggingInterceptor logging = new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);

/* if(context != null)
token = PreferenceUtils.getToken(context);

if (token != null)
AuthenticationInterceptor authenticationInterceptor =
new AuthenticationInterceptor(token);
httpClient.addInterceptor(authenticationInterceptor);
else
*/
builder.client(httpClient.build());
Retrofit retrofit = builder.build();
return retrofit.create(serviceClass);





Constant



public interface Constant 
String AUTHORIZATION = "AUTHORIZATION";
String TOKEN = "token";
String USER_BASE_URL = "https://192.*********/";
String KEY_USERNAME = "username";
String KEY_EMAIL = "email";
String KEY_NAME = "name";




Model



public class LoginUser 
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;


/**
* No args constructor for use in serialization
*/
public LoginUser()


public LoginUser(String email, String password)
this.email = email;
this.password = password;

public String getEmail()
return email;


public void setEmail(String email)
this.email = email;


public String getPassword()
return password;



public void setPassword(String password)
this.password = password;





public class Message 
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;


/**
* No args constructor for use in serialization
*/
public Message()

public Message(String email, String password)
this.email = email;
this.password = password;


public String getEmail()
return email;


public void setEmail(String email)
this.email = email;


public String getPassword()
return password;



public void setPassword(String password)
this.password = password;





Thanks in advance.










share|improve this question




























    0















    I'm learning REST using Retrofit to register and login on an API in swaggerhub but i'm unable to do it, and it is not showing any error message in my studio. I have google REST AUTHENTICATRION but non of the link was helpful. I have also looked here and here but still couldn't figure it out.



    HERE IS MY SignUpActivity



    public class SignUpActivity extends AppCompatActivity implements View.OnClickListener 
    private EditText mPassword;
    private EditText mPassword2;
    private String password;


    private CountryCodePicker ccp;

    private ProgressDialog pDialog;
    private ProgressBar progressBar;


    LoginServices loginService;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sign_up_activity);




    findViewById(R.id.sign_up_button).setOnClickListener(this);

    mPassword = findViewById(R.id.password);
    mPassword2 = findViewById(R.id.password2);

    progressBar = findViewById(R.id.login_progress);

    loginService = ServiceGenerator.createService(LoginServices.class,
    getApplication(), USER_BASE_URL);


    ccp = findViewById(R.id.ccp);
    EditText mUsername = findViewById(R.id.username);
    ccp.registerCarrierNumberEditText(mUsername);




    private boolean validateForm()

    boolean valid = true;
    View focusView = null;

    password = mPassword.getText().toString();
    // String conPassword = mConfirmPasswordView.getText().toString();
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
    mPassword.setError(getString(R.string.error_invalid_password));
    focusView = mPassword;
    valid = false;
    else
    mPassword.setError(null);


    if (!valid)
    // There was an error; don't attempt login and focus the first
    // form field with an error.
    focusView.requestFocus();

    return valid;


    private boolean isPasswordValid(String password)
    String password2 = mPassword2.getText().toString();
    // Add regex for at least 8 characters including lower case, upper case, digit and special character
    return password.equals(password2) && password.length() >= 6;



    private void submitUserDetails( String email, String password)

    startUi();

    Call<Message> call = loginService.createUser(email, password);

    call.enqueue(new Callback<Message>()
    @Override
    public void onResponse(Call<Message> call, Response<Message> response)
    if (response.isSuccessful())
    // hidepDialog();
    stopUi();
    if (response.body() != null)
    Message message = response.body();
    String regMessage = message.getEmail();
    Log.d("GET INFORMATION: ", call.toString());
    Log.d("GET MESSAGE: ", message.toString());

    Toast.makeText(getApplicationContext(), regMessage + "registered successfully", Toast.LENGTH_SHORT)
    .show();
    Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
    startActivity(intent);
    finish();


    else
    // hidepDialog();
    stopUi();
    Toast.makeText(getApplicationContext(), "error signup user", Toast.LENGTH_SHORT)
    .show();



    @Override
    public void onFailure(Call<Message> call, Throwable t)

    stopUi();
    Toast.makeText(getApplicationContext(), "error registering user "
    + t.getMessage(), Toast.LENGTH_SHORT)
    .show();

    );





    private void startUi()
    progressBar.setVisibility(View.VISIBLE);

    private void stopUi()
    progressBar.setVisibility(View.INVISIBLE);


    @Override
    public void onClick(View view)
    int id = view.getId();
    if (id == R.id.sign_up_button)
    if (validateForm())
    submitUserDetails(ccp.getDefaultCountryCodeWithPlus(), password);





    LoginServices



    public interface LoginServices 

    @FormUrlEncoded
    @POST(Routes.CREATE_USER)
    Call<Message> createUser(@Field("email") String email, @Field("password") String password);

    @FormUrlEncoded
    @POST(Routes.USER_LOGIN)
    Call<LoginUser> userLogin(@Field("email") String email, @Field("password") String password);




    LoginActivity



    public class LoginActivity extends AppCompatActivity implements View.OnClickListener 

    private ProgressDialog pDialog;
    private ProgressBar progressBar;

    private EditText mEtUsername, mEtPassword;
    private String username, password;

    LoginServices loginService;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity);


    progressBar = findViewById(R.id.login_progress);

    mEtUsername = findViewById(R.id.et_login_username);
    mEtPassword = findViewById(R.id.et_login_password);

    findViewById(R.id.btn_login).setOnClickListener(this);
    findViewById(R.id.btn_login_register).setOnClickListener(this);

    loginService = ServiceGenerator.createService(LoginServices.class, getApplication(), USER_BASE_URL);



    private boolean validateForm()

    boolean valid = true;
    View focusView = null;

    username = mEtUsername.getText().toString();
    password = mEtPassword.getText().toString();
    if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
    mEtPassword.setError(getString(R.string.error_invalid_password));
    focusView = mEtPassword;
    valid = false;
    else
    mEtPassword.setError(null);


    // Check for a valid phone number

    if (TextUtils.isEmpty(username))
    mEtUsername.setError("phone number is empty");
    focusView = mEtUsername;
    valid = false;
    else
    mEtUsername.setError(null);

    if (!valid)
    // There was an error; don't attempt login and focus the first
    // form field with an error.
    focusView.requestFocus();

    return valid;


    private boolean isPasswordValid(String password)
    // Add regex for at least 8 characters including lower case, upper case, digit and special character
    return password.length() >= 6;


    private void login(String email, final String password)

    startUi();

    Call<LoginUser> call = loginService.userLogin(email, password);

    call.enqueue(new Callback<LoginUser>()
    @Override
    public void onResponse(Call<LoginUser> call, Response<LoginUser> response)
    if (response.isSuccessful())

    stopUi();

    if (response.body() != null)
    LoginUser message = response.body();

    String email = message.getEmail();
    String password1 = message.getPassword();

    if (password.equals(password1))
    PrefManager.saveEmail(email, getApplicationContext());
    PrefManager.saveUsername(username, getApplicationContext());

    Toast.makeText(getApplicationContext(), "user authenticated successfully "
    + email, Toast.LENGTH_SHORT)
    .show();
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);
    finish();
    else
    Toast.makeText(getApplicationContext(), "Invalid username or password "
    + email, Toast.LENGTH_SHORT)
    .show();



    else

    stopUi();

    Toast.makeText(getApplicationContext(), "error login user", Toast.LENGTH_SHORT)
    .show();



    @Override
    public void onFailure(Call<LoginUser> call, Throwable t)

    stopUi();

    Toast.makeText(getApplicationContext(), "error registering user " + t.getMessage(), Toast.LENGTH_SHORT)
    .show();

    );


    @Override
    public void onClick(View view)

    switch (view.getId())
    case R.id.btn_login:
    if (validateForm())
    login(username, password);

    break;
    case R.id.btn_login_register:
    startActivity(new Intent(LoginActivity.this,
    SignUpActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    break;


    private void startUi()
    progressBar.setVisibility(View.VISIBLE);

    private void stopUi()
    progressBar.setVisibility(View.INVISIBLE);





    ServiceGenerator



    public class ServiceGenerator 
    public static <S> S createService(Class<S> serviceClass, Context context, String baseUrl)
    baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
    String token = "";
    Gson gson = new GsonBuilder()
    .enableComplexMapKeySerialization()
    .serializeNulls()
    .setDateFormat(DateFormat.LONG)
    .setPrettyPrinting()
    .setVersion(1.0)
    .create();

    Retrofit.Builder builder = new Retrofit.Builder()
    .addConverterFactory(GsonConverterFactory.create(gson))
    .baseUrl(baseUrl);

    OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
    .readTimeout(90, TimeUnit.SECONDS)
    .connectTimeout(90, TimeUnit.SECONDS)
    .writeTimeout(90, TimeUnit.SECONDS)
    .cache(null);

    if (BuildConfig.DEBUG)
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor()
    .setLevel(HttpLoggingInterceptor.Level.BODY);
    httpClient.addInterceptor(logging);

    /* if(context != null)
    token = PreferenceUtils.getToken(context);

    if (token != null)
    AuthenticationInterceptor authenticationInterceptor =
    new AuthenticationInterceptor(token);
    httpClient.addInterceptor(authenticationInterceptor);
    else
    */
    builder.client(httpClient.build());
    Retrofit retrofit = builder.build();
    return retrofit.create(serviceClass);





    Constant



    public interface Constant 
    String AUTHORIZATION = "AUTHORIZATION";
    String TOKEN = "token";
    String USER_BASE_URL = "https://192.*********/";
    String KEY_USERNAME = "username";
    String KEY_EMAIL = "email";
    String KEY_NAME = "name";




    Model



    public class LoginUser 
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("password")
    @Expose
    private String password;


    /**
    * No args constructor for use in serialization
    */
    public LoginUser()


    public LoginUser(String email, String password)
    this.email = email;
    this.password = password;

    public String getEmail()
    return email;


    public void setEmail(String email)
    this.email = email;


    public String getPassword()
    return password;



    public void setPassword(String password)
    this.password = password;





    public class Message 
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("password")
    @Expose
    private String password;


    /**
    * No args constructor for use in serialization
    */
    public Message()

    public Message(String email, String password)
    this.email = email;
    this.password = password;


    public String getEmail()
    return email;


    public void setEmail(String email)
    this.email = email;


    public String getPassword()
    return password;



    public void setPassword(String password)
    this.password = password;





    Thanks in advance.










    share|improve this question


























      0












      0








      0


      1






      I'm learning REST using Retrofit to register and login on an API in swaggerhub but i'm unable to do it, and it is not showing any error message in my studio. I have google REST AUTHENTICATRION but non of the link was helpful. I have also looked here and here but still couldn't figure it out.



      HERE IS MY SignUpActivity



      public class SignUpActivity extends AppCompatActivity implements View.OnClickListener 
      private EditText mPassword;
      private EditText mPassword2;
      private String password;


      private CountryCodePicker ccp;

      private ProgressDialog pDialog;
      private ProgressBar progressBar;


      LoginServices loginService;
      @Override
      protected void onCreate(Bundle savedInstanceState)
      super.onCreate(savedInstanceState);
      setContentView(R.layout.sign_up_activity);




      findViewById(R.id.sign_up_button).setOnClickListener(this);

      mPassword = findViewById(R.id.password);
      mPassword2 = findViewById(R.id.password2);

      progressBar = findViewById(R.id.login_progress);

      loginService = ServiceGenerator.createService(LoginServices.class,
      getApplication(), USER_BASE_URL);


      ccp = findViewById(R.id.ccp);
      EditText mUsername = findViewById(R.id.username);
      ccp.registerCarrierNumberEditText(mUsername);




      private boolean validateForm()

      boolean valid = true;
      View focusView = null;

      password = mPassword.getText().toString();
      // String conPassword = mConfirmPasswordView.getText().toString();
      if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
      mPassword.setError(getString(R.string.error_invalid_password));
      focusView = mPassword;
      valid = false;
      else
      mPassword.setError(null);


      if (!valid)
      // There was an error; don't attempt login and focus the first
      // form field with an error.
      focusView.requestFocus();

      return valid;


      private boolean isPasswordValid(String password)
      String password2 = mPassword2.getText().toString();
      // Add regex for at least 8 characters including lower case, upper case, digit and special character
      return password.equals(password2) && password.length() >= 6;



      private void submitUserDetails( String email, String password)

      startUi();

      Call<Message> call = loginService.createUser(email, password);

      call.enqueue(new Callback<Message>()
      @Override
      public void onResponse(Call<Message> call, Response<Message> response)
      if (response.isSuccessful())
      // hidepDialog();
      stopUi();
      if (response.body() != null)
      Message message = response.body();
      String regMessage = message.getEmail();
      Log.d("GET INFORMATION: ", call.toString());
      Log.d("GET MESSAGE: ", message.toString());

      Toast.makeText(getApplicationContext(), regMessage + "registered successfully", Toast.LENGTH_SHORT)
      .show();
      Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
      startActivity(intent);
      finish();


      else
      // hidepDialog();
      stopUi();
      Toast.makeText(getApplicationContext(), "error signup user", Toast.LENGTH_SHORT)
      .show();



      @Override
      public void onFailure(Call<Message> call, Throwable t)

      stopUi();
      Toast.makeText(getApplicationContext(), "error registering user "
      + t.getMessage(), Toast.LENGTH_SHORT)
      .show();

      );





      private void startUi()
      progressBar.setVisibility(View.VISIBLE);

      private void stopUi()
      progressBar.setVisibility(View.INVISIBLE);


      @Override
      public void onClick(View view)
      int id = view.getId();
      if (id == R.id.sign_up_button)
      if (validateForm())
      submitUserDetails(ccp.getDefaultCountryCodeWithPlus(), password);





      LoginServices



      public interface LoginServices 

      @FormUrlEncoded
      @POST(Routes.CREATE_USER)
      Call<Message> createUser(@Field("email") String email, @Field("password") String password);

      @FormUrlEncoded
      @POST(Routes.USER_LOGIN)
      Call<LoginUser> userLogin(@Field("email") String email, @Field("password") String password);




      LoginActivity



      public class LoginActivity extends AppCompatActivity implements View.OnClickListener 

      private ProgressDialog pDialog;
      private ProgressBar progressBar;

      private EditText mEtUsername, mEtPassword;
      private String username, password;

      LoginServices loginService;
      @Override
      protected void onCreate(Bundle savedInstanceState)
      super.onCreate(savedInstanceState);
      setContentView(R.layout.login_activity);


      progressBar = findViewById(R.id.login_progress);

      mEtUsername = findViewById(R.id.et_login_username);
      mEtPassword = findViewById(R.id.et_login_password);

      findViewById(R.id.btn_login).setOnClickListener(this);
      findViewById(R.id.btn_login_register).setOnClickListener(this);

      loginService = ServiceGenerator.createService(LoginServices.class, getApplication(), USER_BASE_URL);



      private boolean validateForm()

      boolean valid = true;
      View focusView = null;

      username = mEtUsername.getText().toString();
      password = mEtPassword.getText().toString();
      if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
      mEtPassword.setError(getString(R.string.error_invalid_password));
      focusView = mEtPassword;
      valid = false;
      else
      mEtPassword.setError(null);


      // Check for a valid phone number

      if (TextUtils.isEmpty(username))
      mEtUsername.setError("phone number is empty");
      focusView = mEtUsername;
      valid = false;
      else
      mEtUsername.setError(null);

      if (!valid)
      // There was an error; don't attempt login and focus the first
      // form field with an error.
      focusView.requestFocus();

      return valid;


      private boolean isPasswordValid(String password)
      // Add regex for at least 8 characters including lower case, upper case, digit and special character
      return password.length() >= 6;


      private void login(String email, final String password)

      startUi();

      Call<LoginUser> call = loginService.userLogin(email, password);

      call.enqueue(new Callback<LoginUser>()
      @Override
      public void onResponse(Call<LoginUser> call, Response<LoginUser> response)
      if (response.isSuccessful())

      stopUi();

      if (response.body() != null)
      LoginUser message = response.body();

      String email = message.getEmail();
      String password1 = message.getPassword();

      if (password.equals(password1))
      PrefManager.saveEmail(email, getApplicationContext());
      PrefManager.saveUsername(username, getApplicationContext());

      Toast.makeText(getApplicationContext(), "user authenticated successfully "
      + email, Toast.LENGTH_SHORT)
      .show();
      Intent intent = new Intent(LoginActivity.this, MainActivity.class);
      startActivity(intent);
      finish();
      else
      Toast.makeText(getApplicationContext(), "Invalid username or password "
      + email, Toast.LENGTH_SHORT)
      .show();



      else

      stopUi();

      Toast.makeText(getApplicationContext(), "error login user", Toast.LENGTH_SHORT)
      .show();



      @Override
      public void onFailure(Call<LoginUser> call, Throwable t)

      stopUi();

      Toast.makeText(getApplicationContext(), "error registering user " + t.getMessage(), Toast.LENGTH_SHORT)
      .show();

      );


      @Override
      public void onClick(View view)

      switch (view.getId())
      case R.id.btn_login:
      if (validateForm())
      login(username, password);

      break;
      case R.id.btn_login_register:
      startActivity(new Intent(LoginActivity.this,
      SignUpActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
      break;


      private void startUi()
      progressBar.setVisibility(View.VISIBLE);

      private void stopUi()
      progressBar.setVisibility(View.INVISIBLE);





      ServiceGenerator



      public class ServiceGenerator 
      public static <S> S createService(Class<S> serviceClass, Context context, String baseUrl)
      baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
      String token = "";
      Gson gson = new GsonBuilder()
      .enableComplexMapKeySerialization()
      .serializeNulls()
      .setDateFormat(DateFormat.LONG)
      .setPrettyPrinting()
      .setVersion(1.0)
      .create();

      Retrofit.Builder builder = new Retrofit.Builder()
      .addConverterFactory(GsonConverterFactory.create(gson))
      .baseUrl(baseUrl);

      OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
      .readTimeout(90, TimeUnit.SECONDS)
      .connectTimeout(90, TimeUnit.SECONDS)
      .writeTimeout(90, TimeUnit.SECONDS)
      .cache(null);

      if (BuildConfig.DEBUG)
      HttpLoggingInterceptor logging = new HttpLoggingInterceptor()
      .setLevel(HttpLoggingInterceptor.Level.BODY);
      httpClient.addInterceptor(logging);

      /* if(context != null)
      token = PreferenceUtils.getToken(context);

      if (token != null)
      AuthenticationInterceptor authenticationInterceptor =
      new AuthenticationInterceptor(token);
      httpClient.addInterceptor(authenticationInterceptor);
      else
      */
      builder.client(httpClient.build());
      Retrofit retrofit = builder.build();
      return retrofit.create(serviceClass);





      Constant



      public interface Constant 
      String AUTHORIZATION = "AUTHORIZATION";
      String TOKEN = "token";
      String USER_BASE_URL = "https://192.*********/";
      String KEY_USERNAME = "username";
      String KEY_EMAIL = "email";
      String KEY_NAME = "name";




      Model



      public class LoginUser 
      @SerializedName("email")
      @Expose
      private String email;
      @SerializedName("password")
      @Expose
      private String password;


      /**
      * No args constructor for use in serialization
      */
      public LoginUser()


      public LoginUser(String email, String password)
      this.email = email;
      this.password = password;

      public String getEmail()
      return email;


      public void setEmail(String email)
      this.email = email;


      public String getPassword()
      return password;



      public void setPassword(String password)
      this.password = password;





      public class Message 
      @SerializedName("email")
      @Expose
      private String email;
      @SerializedName("password")
      @Expose
      private String password;


      /**
      * No args constructor for use in serialization
      */
      public Message()

      public Message(String email, String password)
      this.email = email;
      this.password = password;


      public String getEmail()
      return email;


      public void setEmail(String email)
      this.email = email;


      public String getPassword()
      return password;



      public void setPassword(String password)
      this.password = password;





      Thanks in advance.










      share|improve this question
















      I'm learning REST using Retrofit to register and login on an API in swaggerhub but i'm unable to do it, and it is not showing any error message in my studio. I have google REST AUTHENTICATRION but non of the link was helpful. I have also looked here and here but still couldn't figure it out.



      HERE IS MY SignUpActivity



      public class SignUpActivity extends AppCompatActivity implements View.OnClickListener 
      private EditText mPassword;
      private EditText mPassword2;
      private String password;


      private CountryCodePicker ccp;

      private ProgressDialog pDialog;
      private ProgressBar progressBar;


      LoginServices loginService;
      @Override
      protected void onCreate(Bundle savedInstanceState)
      super.onCreate(savedInstanceState);
      setContentView(R.layout.sign_up_activity);




      findViewById(R.id.sign_up_button).setOnClickListener(this);

      mPassword = findViewById(R.id.password);
      mPassword2 = findViewById(R.id.password2);

      progressBar = findViewById(R.id.login_progress);

      loginService = ServiceGenerator.createService(LoginServices.class,
      getApplication(), USER_BASE_URL);


      ccp = findViewById(R.id.ccp);
      EditText mUsername = findViewById(R.id.username);
      ccp.registerCarrierNumberEditText(mUsername);




      private boolean validateForm()

      boolean valid = true;
      View focusView = null;

      password = mPassword.getText().toString();
      // String conPassword = mConfirmPasswordView.getText().toString();
      if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
      mPassword.setError(getString(R.string.error_invalid_password));
      focusView = mPassword;
      valid = false;
      else
      mPassword.setError(null);


      if (!valid)
      // There was an error; don't attempt login and focus the first
      // form field with an error.
      focusView.requestFocus();

      return valid;


      private boolean isPasswordValid(String password)
      String password2 = mPassword2.getText().toString();
      // Add regex for at least 8 characters including lower case, upper case, digit and special character
      return password.equals(password2) && password.length() >= 6;



      private void submitUserDetails( String email, String password)

      startUi();

      Call<Message> call = loginService.createUser(email, password);

      call.enqueue(new Callback<Message>()
      @Override
      public void onResponse(Call<Message> call, Response<Message> response)
      if (response.isSuccessful())
      // hidepDialog();
      stopUi();
      if (response.body() != null)
      Message message = response.body();
      String regMessage = message.getEmail();
      Log.d("GET INFORMATION: ", call.toString());
      Log.d("GET MESSAGE: ", message.toString());

      Toast.makeText(getApplicationContext(), regMessage + "registered successfully", Toast.LENGTH_SHORT)
      .show();
      Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
      startActivity(intent);
      finish();


      else
      // hidepDialog();
      stopUi();
      Toast.makeText(getApplicationContext(), "error signup user", Toast.LENGTH_SHORT)
      .show();



      @Override
      public void onFailure(Call<Message> call, Throwable t)

      stopUi();
      Toast.makeText(getApplicationContext(), "error registering user "
      + t.getMessage(), Toast.LENGTH_SHORT)
      .show();

      );





      private void startUi()
      progressBar.setVisibility(View.VISIBLE);

      private void stopUi()
      progressBar.setVisibility(View.INVISIBLE);


      @Override
      public void onClick(View view)
      int id = view.getId();
      if (id == R.id.sign_up_button)
      if (validateForm())
      submitUserDetails(ccp.getDefaultCountryCodeWithPlus(), password);





      LoginServices



      public interface LoginServices 

      @FormUrlEncoded
      @POST(Routes.CREATE_USER)
      Call<Message> createUser(@Field("email") String email, @Field("password") String password);

      @FormUrlEncoded
      @POST(Routes.USER_LOGIN)
      Call<LoginUser> userLogin(@Field("email") String email, @Field("password") String password);




      LoginActivity



      public class LoginActivity extends AppCompatActivity implements View.OnClickListener 

      private ProgressDialog pDialog;
      private ProgressBar progressBar;

      private EditText mEtUsername, mEtPassword;
      private String username, password;

      LoginServices loginService;
      @Override
      protected void onCreate(Bundle savedInstanceState)
      super.onCreate(savedInstanceState);
      setContentView(R.layout.login_activity);


      progressBar = findViewById(R.id.login_progress);

      mEtUsername = findViewById(R.id.et_login_username);
      mEtPassword = findViewById(R.id.et_login_password);

      findViewById(R.id.btn_login).setOnClickListener(this);
      findViewById(R.id.btn_login_register).setOnClickListener(this);

      loginService = ServiceGenerator.createService(LoginServices.class, getApplication(), USER_BASE_URL);



      private boolean validateForm()

      boolean valid = true;
      View focusView = null;

      username = mEtUsername.getText().toString();
      password = mEtPassword.getText().toString();
      if (!TextUtils.isEmpty(password) && !isPasswordValid(password))
      mEtPassword.setError(getString(R.string.error_invalid_password));
      focusView = mEtPassword;
      valid = false;
      else
      mEtPassword.setError(null);


      // Check for a valid phone number

      if (TextUtils.isEmpty(username))
      mEtUsername.setError("phone number is empty");
      focusView = mEtUsername;
      valid = false;
      else
      mEtUsername.setError(null);

      if (!valid)
      // There was an error; don't attempt login and focus the first
      // form field with an error.
      focusView.requestFocus();

      return valid;


      private boolean isPasswordValid(String password)
      // Add regex for at least 8 characters including lower case, upper case, digit and special character
      return password.length() >= 6;


      private void login(String email, final String password)

      startUi();

      Call<LoginUser> call = loginService.userLogin(email, password);

      call.enqueue(new Callback<LoginUser>()
      @Override
      public void onResponse(Call<LoginUser> call, Response<LoginUser> response)
      if (response.isSuccessful())

      stopUi();

      if (response.body() != null)
      LoginUser message = response.body();

      String email = message.getEmail();
      String password1 = message.getPassword();

      if (password.equals(password1))
      PrefManager.saveEmail(email, getApplicationContext());
      PrefManager.saveUsername(username, getApplicationContext());

      Toast.makeText(getApplicationContext(), "user authenticated successfully "
      + email, Toast.LENGTH_SHORT)
      .show();
      Intent intent = new Intent(LoginActivity.this, MainActivity.class);
      startActivity(intent);
      finish();
      else
      Toast.makeText(getApplicationContext(), "Invalid username or password "
      + email, Toast.LENGTH_SHORT)
      .show();



      else

      stopUi();

      Toast.makeText(getApplicationContext(), "error login user", Toast.LENGTH_SHORT)
      .show();



      @Override
      public void onFailure(Call<LoginUser> call, Throwable t)

      stopUi();

      Toast.makeText(getApplicationContext(), "error registering user " + t.getMessage(), Toast.LENGTH_SHORT)
      .show();

      );


      @Override
      public void onClick(View view)

      switch (view.getId())
      case R.id.btn_login:
      if (validateForm())
      login(username, password);

      break;
      case R.id.btn_login_register:
      startActivity(new Intent(LoginActivity.this,
      SignUpActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
      break;


      private void startUi()
      progressBar.setVisibility(View.VISIBLE);

      private void stopUi()
      progressBar.setVisibility(View.INVISIBLE);





      ServiceGenerator



      public class ServiceGenerator 
      public static <S> S createService(Class<S> serviceClass, Context context, String baseUrl)
      baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
      String token = "";
      Gson gson = new GsonBuilder()
      .enableComplexMapKeySerialization()
      .serializeNulls()
      .setDateFormat(DateFormat.LONG)
      .setPrettyPrinting()
      .setVersion(1.0)
      .create();

      Retrofit.Builder builder = new Retrofit.Builder()
      .addConverterFactory(GsonConverterFactory.create(gson))
      .baseUrl(baseUrl);

      OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
      .readTimeout(90, TimeUnit.SECONDS)
      .connectTimeout(90, TimeUnit.SECONDS)
      .writeTimeout(90, TimeUnit.SECONDS)
      .cache(null);

      if (BuildConfig.DEBUG)
      HttpLoggingInterceptor logging = new HttpLoggingInterceptor()
      .setLevel(HttpLoggingInterceptor.Level.BODY);
      httpClient.addInterceptor(logging);

      /* if(context != null)
      token = PreferenceUtils.getToken(context);

      if (token != null)
      AuthenticationInterceptor authenticationInterceptor =
      new AuthenticationInterceptor(token);
      httpClient.addInterceptor(authenticationInterceptor);
      else
      */
      builder.client(httpClient.build());
      Retrofit retrofit = builder.build();
      return retrofit.create(serviceClass);





      Constant



      public interface Constant 
      String AUTHORIZATION = "AUTHORIZATION";
      String TOKEN = "token";
      String USER_BASE_URL = "https://192.*********/";
      String KEY_USERNAME = "username";
      String KEY_EMAIL = "email";
      String KEY_NAME = "name";




      Model



      public class LoginUser 
      @SerializedName("email")
      @Expose
      private String email;
      @SerializedName("password")
      @Expose
      private String password;


      /**
      * No args constructor for use in serialization
      */
      public LoginUser()


      public LoginUser(String email, String password)
      this.email = email;
      this.password = password;

      public String getEmail()
      return email;


      public void setEmail(String email)
      this.email = email;


      public String getPassword()
      return password;



      public void setPassword(String password)
      this.password = password;





      public class Message 
      @SerializedName("email")
      @Expose
      private String email;
      @SerializedName("password")
      @Expose
      private String password;


      /**
      * No args constructor for use in serialization
      */
      public Message()

      public Message(String email, String password)
      this.email = email;
      this.password = password;


      public String getEmail()
      return email;


      public void setEmail(String email)
      this.email = email;


      public String getPassword()
      return password;



      public void setPassword(String password)
      this.password = password;





      Thanks in advance.







      authentication retrofit






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 '18 at 21:28







      James

















      asked Nov 11 '18 at 21:05









      JamesJames

      127




      127






















          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253235%2fapi-user-authentication-using-retrofit%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253235%2fapi-user-authentication-using-retrofit%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Crossroads (UK TV series)

          ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế