Search code examples
androidretrofitretrofit2

How to identify if the JSON response data is empty or not from server using Retrofit?


I am retrieveing a list of data from server to be displayed into recyclerview in android using retrofit.
The retrieval is working fine, the data called is displayed and no problem.

But the problem is, I want to check if the data I get is empty or not, because I want to do some action from this checking.

I've tried this code but it keeps checking only successful do the request, not the JSON data content that it brought from server.

getData.enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {

if (response.body() != null){
Toast.makeText(getApplicationContext(), "Data is not empty", Toast.LENGTH_LONG).show();
} else {
// want to do some action here after the checking
Toast.makeText(getApplicationContext(), "Data isempty", Toast.LENGTH_LONG).show();
}
someList = new ArrayList<ModelItem>();
someList= response.body().getItem();
adapter= new Adapter(getApplicationContext(), someList);

recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}

@Override
public void onFailure(Call<Model> call, Throwable t) {
Toast.makeText(getApplicationContext(), getString(R.string.error_connection), Toast.LENGTH_LONG).show();
}
});

I want to check the inner response if it empty or not, thanks


Solution

  • use below code, before you map Json to POJO.

    String response = basicResponse.getResponse();
    if(response!=null){
       String responseBody = response.body();
       if(!responseBody.isEmpty()){
          // non empty response, you can map Json via Gson to POJO classes...
    
       }
       else{
           // empty response...
       }
    }