Yousef Elsayed
Yousef Elsayed

Reputation: 145

Method always return empty list

I am using mvp Design pattern in android development and i am using retrofit2 with it ... when i run the function to get me information from a the web it get the information but returns null list

the Response.Body come with response that mean that the code works

the model function

    List<SearchDdb> searchResult;
    private Context context;
    public MainModel(Context context){this.context=context;}
    public List<SearchDdb> searchUser(String name) {
        final MainPresenter presenter = new MainPresenter(context);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Db db = retrofit.create(Db.class);
        Call<List<SearchDdb>> call = db.getUsers(name);
        call.enqueue(new Callback<List<SearchDdb>>() {
            @Override
            public void onResponse(Call<List<SearchDdb>> call, Response<List<SearchDdb>> response) {
                if(!response.isSuccessful()){
                    presenter.showDialog();
                }
               searchResult = response.body();
            }

            @Override
            public void onFailure(Call<List<SearchDdb>> call, Throwable t) {
            }
        });
        return searchResult;
    }

the SearchDdb file

    private int id;
    private String name;
    private String grade;
    private String age;
    private String address;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getGrade() {
        return grade;
    }

    public String getAge() {
        return age;
    }

    public String getAddress() {
        return address;
    }
}

How i call the function List<SearchDdb> ressult = presenter.searchUser("1");

Upvotes: 0

Views: 525

Answers (1)

faranjit
faranjit

Reputation: 1627

You cant call it like List<SearchDdb> ressult = presenter.searchUser("1"); because searchUser method makes an async request via retrofit. This way searchUse returns null searchResult because response has not come yet.

Define a LiveData in your viewmodel class and observe it in your activity/fragment. When response comes from api in onResponse in searchUser post that response to live data and use it where you observe.

If you want to see a tutorial you can look at this article.

Here is another example.

Upvotes: 2

Related Questions