lundi 16 novembre 2020

Android User Login with Retrofit using my own API

I am trying to use my own login api via retrofit. The Problem is, if username and password is correct, nothing happens and a toast with the message doesn't appears. But if the username and password is wrong, i get a right response and the toast with the correct message appears?

LoginActivity.java:

package com.example.retrofittestproject;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextUsername;
    private EditText editTextPassword;

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

        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);

        findViewById(R.id.buttonLogin).setOnClickListener(this);
        findViewById(R.id.textViewRegister).setOnClickListener(this);
    }

    private void userLogin(){

        String name = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if(name.isEmpty()){
            editTextUsername.setError("Username is required");
            editTextUsername.requestFocus();
            return;
        }

        if(password.isEmpty()){
            editTextPassword.setError("Password required");
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6){
            editTextPassword.setError("Password should be at least 6 character long");
            editTextPassword.requestFocus();
            return;
        }

        Call<LoginResponse> call = RetrofitClient
                .getInstance().getApi().userLogin(name, password);

        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                LoginResponse loginResponse = response.body();

                if(loginResponse.isError() == false){
                    //save User
                    //open Profile
                    Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e("Login: ", "Login successfully!");
                }
                else {
                    //User not found
                    Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
                    Log.e("Login: ", "Login NOT successfully!");
                }
                Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_LONG).show();
            }

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

            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonLogin:
                userLogin();
                break;
            case R.id.textViewRegister:
                break;
        }
    }
}

RetrofitClient.java

package com.example.retrofittestproject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static String BASE_URL = "https://lookly.hasp-teach.eu/api/";
    private static String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFuZHJvaWQtY2xpZW50Iiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNjA1MTEzODkwfQ.bf6ffycsoN64n35iseMyBX1HiB9GjiqA9xfPNF1GWHw";
    private static RetrofitClient mInstance;
    private Retrofit retrofit;


    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request newRequest  = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
            return chain.proceed(newRequest);
        }
    }).build();


    private RetrofitClient(){
        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized RetrofitClient getInstance(){
        if(mInstance == null){
            mInstance = new RetrofitClient();
        }
        return mInstance;
    }

    public Api getApi(){
        return retrofit.create(Api.class);
    }
}

Api.java

package com.example.retrofittestproject;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface Api {
    @FormUrlEncoded
    @POST("userLogin")
    Call<LoginResponse> userLogin(
            @Field("name") String name,
            @Field("password") String password
    );
}

LoginResponse.java

package com.example.retrofittestproject;

public class LoginResponse {
    private boolean error;
    private String message;
    private User user;

    public LoginResponse(boolean error, String message, User user) {
        this.error = error;
        this.message = message;
        this.user = user;
    }

    public boolean isError() { return error; }
    public void setError(boolean value) { this.error = value; }

    public String getMessage() { return message; }
    public void setMessage(String value) { this.message = value; }

    public User getUser() { return user; }
    public void setUser(User value) { this.user = value; }
}

User.java

package com.example.retrofittestproject;

import java.time.OffsetDateTime;

    public class User {
        private long userID;
        private String userName;
        private String firstName;
        private String lastName;
        private String email;
        private Object street;
        private String town;
        private String country;
        private String gender;
        private OffsetDateTime birthDate;
        private String status;
        private String aboutmeText;
    
        public User(long userID, String userName, String firstName, String lastName, String email, Object street, String town, String country, String gender, OffsetDateTime birthDate, String status, String aboutmeText) {
            this.userID = userID;
            this.userName = userName;
            this.firstName = firstName;
            this.lastName = lastName;
            this.email = email;
            this.street = street;
            this.town = town;
            this.country = country;
            this.gender = gender;
            this.birthDate = birthDate;
            this.status = status;
            this.aboutmeText = aboutmeText;
        }
    
        public long getUserID() { return userID; }
        public void setUserID(long value) { this.userID = value; }
    
        public String getUserName() { return userName; }
        public void setUserName(String value) { this.userName = value; }
    
        public String getFirstName() { return firstName; }
        public void setFirstName(String value) { this.firstName = value; }
    
        public String getLastName() { return lastName; }
        public void setLastName(String value) { this.lastName = value; }
    
        public String getEmail() { return email; }
        public void setEmail(String value) { this.email = value; }
    
        public Object getStreet() { return street; }
        public void setStreet(Object value) { this.street = value; }
    
        public String getTown() { return town; }
        public void setTown(String value) { this.town = value; }
    
        public String getCountry() { return country; }
        public void setCountry(String value) { this.country = value; }
    
        public String getGender() { return gender; }
        public void setGender(String value) { this.gender = value; }
    
        public OffsetDateTime getBirthDate() { return birthDate; }
        public void setBirthDate(OffsetDateTime value) { this.birthDate = value; }
    
        public String getStatus() { return status; }
        public void setStatus(String value) { this.status = value; }
    
        public String getAboutmeText() { return aboutmeText; }
        public void setAboutmeText(String value) { this.aboutmeText = value; }
    }

Aucun commentaire:

Enregistrer un commentaire