Retrofit - Network call causes app to hang

Viewed 893

I am not able to make a network call using Retrofit and it causes the app to freeze. Below is my code:

RegisterUserApi:

public interface RegisterUserApi
{
    @FormUrlEncoded
    @POST("register.php")
    Call<RegisterUserData> registerUser(
            @Field("email") String email,
            @Field("password") String password
    );
}

RegisterUserData:

public class RegisterUserData
{
    @SerializedName("value")
    private String value;
    @SerializedName("email")
    private String email;

    public RegisterUserData() {}

    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }

    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

RegisterActivity:

Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://www.website.com/")
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

RegisterUserApi registerApi = retrofit.create(RegisterUserApi.class);
System.out.println("inside 1");
Call<RegisterUserData> registerUserDataCall = registerApi.registerUser(email, password);
System.out.println("inside 2");
registerUserDataCall.enqueue(new Callback<RegisterUserData>() {
    @Override
    public void onResponse(@NonNull Call<RegisterUserData> call, retrofit2.Response<RegisterUserData> response) {
        try
        {

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public void onFailure(@NonNull Call<RegisterUserData> call, @NonNull Throwable t) {
        t.printStackTrace();
    }
});

Now on calling this function in RegisterActivity, the logcat is printing "inside 1" but not "inside 2" and causing the app to freeze.

I have no idea what exactly is happening and I am not getting any error in the logcat as well.

Can someone please help me on this ?

gradle:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Also one thing I noticed is if I change the RegisterUserApi and RegisterUserData file names to something else, it might start to work. I have no idea why it is like this

I have same set of files for login as well which works fine.

2 Answers

Just add this line in AndroidManifest.xml

android:usesCleartextTraffic="true" in application tag

You can try to send @Body or @Path.

public interface RegisterUserApi
{
    @FormUrlEncoded
    @POST("register.php")
    Call<RegisterUserData> registerUser(
        @Path("email") String email,
        @Path("password") String password
);
}

or

 public interface RegisterUserApi
{
    @FormUrlEncoded
    @POST("register.php")
    Call<RegisterUserData> registerUser(@Body("userInfo") ModelUserInfo mui);
}
Related