Winner1
Winner1

Reputation: 1526

how to check if Retrofit API call was successful in Android

here is my code:
by this method, I send some data to my API server
if data received successfully success variable will be true inside onResponse method

private boolean success=false;

public boolean commit(){

        requestHandler.insertFields(tableName,values).enqueue(new Callback<DatabaseModel>() {
            @Override
            public void onResponse(Call<DatabaseModel> call,
                                   Response<DatabaseModel> response) {
                if (response.isSuccessful())
                Log.i("debug8","result is:"+response.body().toString());
                else
                    Log.e("debug8","error in server response:"+response.toString());


                success=true;

            }

            @Override
            public void onFailure(Call<DatabaseModel> call, Throwable t) {
                Log.e("tempo",t.getMessage());
            }
        });

        return success;//returns false before finishing the request
}

and in my activity i want to check the result like this:

        Database db=new Database("cars");
    db.put("field1","val1")
            .put("field2","val2");

    if(db.commit())
        Toast.makeText(this, "data inserted successfully", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(this, "failed to insert new record", Toast.LENGTH_SHORT).show();

the problem is that always the commit method result is false because code returns false before retrofit enqueue method finishes its job

is it a good idea to make a custom listener or something like that to do this?
thanks in advance

Upvotes: 2

Views: 7544

Answers (2)

Juan Monsalve
Juan Monsalve

Reputation: 51

what happens there is the next: the request method is an async task, when you call it, it´ll start working on a second plane and your commit function continues with its sync flow which is return (the false value in this case).

you can try 2 things:

  1. something like this,

    public XX(whatever correspond) commit(){
    
    return requestHandler.insertFields(tableName,values).enqueue(new Callback<DatabaseModel>() {
        @Override
        public void onResponse(Call<DatabaseModel> call,
                               Response<DatabaseModel> response) {
            if (response.isSuccessful())
            Log.i("debug8","result is:"+response.body().toString());
            else
                Log.e("debug8","error in server response:"+response.toString());
    
    
             return true;
    
        }
    
        @Override
        public void onFailure(Call<DatabaseModel> call, Throwable t) {
            Log.e("tempo",t.getMessage());   return false;
          }
    });
    

    }

and fix the if at the other side

  1. or this way

    public void commit(){
    
    requestHandler.insertFields(tableName,values).enqueue(new Callback<DatabaseModel>() {
        @Override
        public void onResponse(Call<DatabaseModel> call,
                               Response<DatabaseModel> response) {
            if (response.isSuccessful())
            Log.i("debug8","result is:"+response.body().toString());
            else
                Log.e("debug8","error in server response:"+response.toString());
             Toast.makeText(this, "data inserted successfully", Toast.LENGTH_SHORT).show();
    
        }
    
        @Override
        public void onFailure(Call<DatabaseModel> call, Throwable t) {
            Toast.makeText(this, "failed to insert new record", Toast.LENGTH_SHORT).show();       
                  }
            });}
    

Upvotes: 0

Mayur Gajra
Mayur Gajra

Reputation: 9073

Yes,you need to create listener for this because these calls happen asynchronously that's why it's returning always false.

You can create a interface like below.

public interface RetrofitResponseListener {

    void onSuccess();

    void onFailure();
}

And pass it as a argument in your method.

public void commit(final RetrofitResponseListener retrofitResponseListener) {

        requestHandler.insertFields(tableName, values).enqueue(new Callback<DatabaseModel>() {
            @Override
            public void onResponse(Call<DatabaseModel> call,
                                   Response<DatabaseModel> response) {
                if (response.isSuccessful())
                    retrofitResponseListener.onSuccess();
                else
                    retrofitResponseListener.onFailure();

            }

            @Override
            public void onFailure(Call<DatabaseModel> call, Throwable t) {
                retrofitResponseListener.onFailure();
            }
        });
    }

And finally use this where you like:

private void setListener() {
        commit(new RetrofitResponseListener() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure() {

            }
        });
    } 

Now do anything you want onSuccess or onFailure.

Upvotes: 5

Related Questions