Как улучшить использование нескольких вызовов для модернизации веб-службы API? - PullRequest
0 голосов
/ 03 октября 2018

Я работал над небольшим проектом, чтобы загрузить данные из базы данных и показать их в разных списках через веб-сервис API.

В данный момент я использую следующий подход.Чтобы заполнить один список, я делаю вызов дооснащения и затем передаю его адаптеру для отображения данных.Затем выполните следующий вызов, чтобы заполнить другой список, затем другой, пока весь список не будет заполнен.

enter image description here

Есть ли лучший способ сделать это?

В качестве примера моего вопроса я буду использовать фиктивный функциональный код.

Мой класс фрагмента, куда я отправляю запрос:

public class FragmentDummy extends Fragment {

final private String myURL = "myURL";

private ListView listOne;
private ListView listTwo;
private ListView listThree;

private void initViews(View view) {
    listOne = view.findViewById(R.id.lv_first);
    listTwo = view.findViewById(R.id.lv_second);
    listThree = view.findViewById(R.id.lv_third);
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.test_dummy_layout, container, false);
    initViews(view);
    return view;
}


@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);
    FillListOne();
}


private List<ManagerList> listResponse = new ArrayList<>();

private void FillListOne() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(myURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ServiceList listInfo = retrofit.create(ServiceList.class);
    Call<List<ManagerList>> listRequest = listInfo.getListOne();

    listRequest.enqueue(new Callback<List<ManagerList>>() {
        @Override
        public void onResponse(Call<List<ManagerList>> call, 
   Response<List<ManagerList>> response) {

            listResponse = response.body();

            AdapterList adapterListOne = new AdapterList(getContext(), 
        listResponse);
            listOne.setAdapter(adapterListOne);
        }

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

        }
    });
}

private void FillListTwo() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(myURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ServiceList listInfo = retrofit.create(ServiceList.class);
    Call<List<ManagerList>> listRequest = listInfo.getListTwo();

    listRequest.enqueue(new Callback<List<ManagerList>>() {
        @Override
        public void onResponse(Call<List<ManagerList>> call, 
    Response<List<ManagerList>> response) {

            listResponse = response.body();

            AdapterList adapterListTwo = new AdapterList(getContext(), 
        listResponse);
            listTwo.setAdapter(adapterListTwo);

            FillListThree();
        }

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

        }
    });
}

private void FillListThree() {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(myURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ServiceList listInfo = retrofit.create(ServiceList.class);
    Call<List<ManagerList>> listRequest = listInfo.getListThree();

    listRequest.enqueue(new Callback<List<ManagerList>>() {
        @Override
        public void onResponse(Call<List<ManagerList>> call, Response<List<ManagerList>> response) {

            listResponse = response.body();

            AdapterList adapterListThree = new AdapterList(getContext(), listResponse);
            listThree.setAdapter(adapterListThree);
        }

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

        }
    });
}


 }

Мой класс интерфейса:

public interface ServiceList {


@GET("api/listOne")
Call<List<ManagerList>> getListOne();

@GET("api/listTwo")
Call<List<ManagerList>> getListTwo();

@GET("api/listTree")
Call<List<ManagerList>> getListThree();

}

Класс ManagerList - это место, где я определяю структуру объекта.

Класс AdapterList - это класс для заполнения ListView.

Мой макет xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="center"
tools:context=".FragmentDummy">

<TextView
    android:id="@+id/tv_firstTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="10dp"
    android:text="First List"
    android:textStyle="bold"
    android:textAlignment="center"
    android:textColor="@color/white"
    android:background="@color/steelblue"
    android:textSize="@dimen/title_size"/>

<ListView
    android:id="@+id/lv_first"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:textAlignment="center"
    android:layout_marginBottom="10dp"
    android:textSize="@dimen/info_size" />

<TextView
    android:id="@+id/tv_secondTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="10dp"
    android:text="Second List"
    android:textStyle="bold"
    android:textAlignment="center"
    android:textColor="@color/white"
    android:background="@color/steelblue"
    android:textSize="@dimen/title_size"/>

<ListView
    android:id="@+id/lv_second"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:textAlignment="center"
    android:layout_marginBottom="10dp"
    android:textSize="@dimen/info_size" />


<TextView
    android:id="@+id/tv_thirdTitle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="10dp"
    android:text="Third List"
    android:textStyle="bold"
    android:textAlignment="center"
    android:textColor="@color/white"
    android:background="@color/steelblue"
    android:textSize="@dimen/title_size"/>

<ListView
    android:id="@+id/lv_third"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:textAlignment="center"
    android:layout_marginBottom="10dp"
    android:textSize="@dimen/info_size" />

</LinearLayout>

Я читал, что с помощью Rx Java это можно улучшить и оптимизировать, однако тема огромна, и я не знаю, с чего начать, чтобы улучшить мой код.

Я знаю, что могу использовать ReciclerView вместо ListView, но только для иллюстрации вызовов службы.

...