如何在android中的自定义采用者中使用json数组列表?

时间:2017-04-11 23:06:18

标签: android android-recyclerview android-adapter android-json

我想从android中的服务器调用json API:

enter image description here

STEP1

我在一个json中有2个列表。(菜单和结果)

{
"page": 1, 
    "menus": [ { m1:"v1" },{ ... },..., "count_menus": 10],
    "results": [ { r1:"v1",r2:"v2" },{ ... },"count_results": 273 ]
, "total_count": 5450, "total_pages": 283 

}

问题1 :首先,json结构是真的吗?

---------

我创建了一个MedicAPI.java类:

public class MedicApi {

    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl("http://www.example.com/api/")
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

public interface MedicService {

    @GET("service/last.php")
    Call<LastMedic> getTopRatedMovies(
            @Query("api_key") String apiKey,
            @Query("language") String language,
            @Query("page") int pageIndex
    );

}

现在,我为此创建了一些模型:

public class LastMedic {

    @SerializedName("page")
    @Expose
    private Integer page;
    @SerializedName("results")
    @Expose
    private List<LastMedicResult> results = new ArrayList<LastMedicResult>();
    @SerializedName("menus")
    @Expose
    private List<LastMedicMenu> menus = new ArrayList<LastMedicMenu>();
    @SerializedName("total_counts")
    @Expose
    private Integer totalCounts;
    @SerializedName("total_pages")
    @Expose
    private Integer totalPages;


    public Integer getPage() {
        return page;
    }
    public void setPage(Integer page) {
        this.page = page;
    }
    public List<LastMedicResult> getResults() {
        return results;
    }
    public void setResults(List<LastMedicResult> results) {
        this.results = results;
    }
    public List<LastMedicMenu> getMenus() {
        return menus;
    }
    public void setMenus(List<LastMedicMenu> menus) {
        this.menus = menus;
    }
    public Integer gettotalCounts() {
        return totalCounts;
    }
    public void settotalCounts(Integer totalCounts) {
        this.totalCounts = totalCounts;
    }
    public Integer getTotalPages() {
        return totalPages;
    }
    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

}

还有两个菜单和结果模型 LastMedicMenu LastMedicResults

所以我认为我的代码已经完成了API。

第1步,在另一个项目中工作

STEP2

我使用this library adopter

这是 Dataserver.java

中的示例数据
public class DataServer {

    private DataServer() {

    }

    public static List<MultipleItem> getMultipleItemData() {

        List<MultipleItem> list = new ArrayList<>();



            for (int i = 0; i <= 5; i++) {
                thisCounter++;
                list.add(new MultipleItem(MultipleItem.IMG_TEXT, MultipleItem.IMG_TEXT_SPAN_SIZE_MIN,"menu"));
           }


        for (int i = 0; i <= 10; i++) {
            list.add(new MultipleItem(MultipleItem.SERVICE_LIST, MultipleItem.SERVICE_SPAN_SIZE));
        }

    }
}

public class MultipleItem implements MultiItemEntity {

    public static final int TEXT = 1;
    public static final int TEXT_SPAN_SIZE = 4;
    public static final int IMG = 2;
    public static final int IMG_SPAN_SIZE = 1;
    public static final int IMG_TEXT = 3;
    public static final int IMG_TEXT_SPAN_SIZE = 4;
    public static final int IMG_TEXT_SPAN_SIZE_MIN = 2;
    public static final int SERVICE_LIST = 4;
    public static final int SERVICE_SPAN_SIZE = 4;

    private int itemType;
    private int spanSize;


    public MultipleItem(int itemType, int spanSize, String content) {
        this.itemType = itemType;
        this.spanSize = spanSize;
        this.content = content;
    }

    public MultipleItem(int itemType, int spanSize) {
        this.itemType = itemType;
        this.spanSize = spanSize;
    }

    public int getSpanSize() {
        return spanSize;
    }

    public void setSpanSize(int spanSize) {
        this.spanSize = spanSize;
    }

    private String content;
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public int getItemType() {
        return itemType;
    }
}

第2步,适用于样本数据。

例如,我可以在adobter中使用此代码绑定XML:

protected void convert(BaseViewHolder helper, MultipleItem item) {
        switch (helper.getItemViewType()) {
            case MultipleItem.TEXT:
                helper.setText(R.id.tv, item.getContent());

STEP3

现在,我想要合并Step1和Step2。

我的意思是我想用json数据代替样本数据。

例如:

for (int i = 0; i <= 5; i++) {
                    thisCounter++;
                    list.add(new MultipleItem(MultipleItem.IMG_TEXT, MultipleItem.IMG_TEXT_SPAN_SIZE_MIN,"menu"));
               }

我想在json中使用菜单列表。

并为此

for (int i = 0; i <= 10; i++) {
            list.add(new MultipleItem(MultipleItem.SERVICE_LIST, MultipleItem.SERVICE_SPAN_SIZE));
}

我想在json中使用结果列表。

第4步 此代码是否适用于加载列表表单服务器?

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


                List<LastMedicResult> results = fetchResults(response);
                List<LastMedicMenu> menus = fetchResults2(response);

            }

            @Override
            public void onFailure(Call<LastMedic> call, Throwable t) {
                t.printStackTrace();
                // 
            }
        });

private Call<LastMedic> callLastMedicApi() {
    return medicService.getTopRatedMovies(
            getString(R.string.my_api_key),
            "en_US",
            currentPage
    );
}

如果是,如何使用此代码和DataServer类以及MultipleItem类?

我想要这样做(例如):

protected void convert(BaseViewHolder helper, MultipleItem item) {
            switch (helper.getItemViewType()) {
                case MultipleItem.TEXT:
                    helper.setText(R.id.tv, item.getMenu(M1));

1 个答案:

答案 0 :(得分:0)

public class DataServer {

    private DataServer() {

    }

    public static List<MultipleItem> getMultipleItemData(List<LastMedicResult> results,List<LastMedicMenu> menus) {

        List<MultipleItem> list = new ArrayList<>();



            for (int i = 0; i <= menus.size(); i++) {
                thisCounter++;
                list.add(new MultipleItem(MultipleItem.IMG_TEXT, MultipleItem.IMG_TEXT_SPAN_SIZE_MIN,"menu"));
           }


        for (int i = 0; i <= results.size(); i++) {
            list.add(new MultipleItem(MultipleItem.SERVICE_LIST, MultipleItem.SERVICE_SPAN_SIZE));
        }

    }
}

执行此操作后,请在响应中调用getMultipleItemData

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


                        List<LastMedicResult> results = fetchResults(response);
                        List<LastMedicMenu> menus = fetchResults2(response);

mRecyclerView = (RecyclerView) findViewById(R.id.YOUR_RECYCLERVIEW_ID);
                   final List<MultipleItem> dataList =     DataServer.getMultipleItemData(results,menus); //it will return a list and you can send this list in MultipleItemQuickAdapter

      /* i get this code from the library that you share above */
            final MultipleItemQuickAdapter multipleItemAdapter = new MultipleItemQuickAdapter(YOUR_ACTIVITY.this, dataList); // your datas.
            final GridLayoutManager manager = new GridLayoutManager(this, 4);
            mRecyclerView.setLayoutManager(manager);
            multipleItemAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
                @Override
                public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                    return data.get(position).getSpanSize();
                }
            });
            mRecyclerView.setAdapter(multipleItemAdapter);
                    }

                    @Override
                    public void onFailure(Call<LastMedic> call, Throwable t) {
                        t.printStackTrace();
                        // 
                    }
                });

        private Call<LastMedic> callLastMedicApi() {
            return medicService.getTopRatedMovies(
                    getString(R.string.my_api_key),
                    "en_US",
                    currentPage
            );
        }