解析嵌套的JSON值并在对日期进行排序时显示在recyclerview中

时间:2018-07-15 06:00:36

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

所以我必须解析以下JSON并在两步回收视图中显示数据,即,在第一个屏幕上,应用程序应仅显示“关联名称”和“金额”,

something like this

但是,如果我单击某个列表项,它也应该显示其余数据。

此外,我知道我必须为实现Comparable接口的响应创建一个Model类。

此类将覆盖compareTo方法,该方法将基于transaction_date对交易进行排序。 但是我无所适从,因为我生成POJO类时会得到四个不同的Java类(Transaction,Datum,Card,Associate)。在创建用于recyclerview的适配器时,我无法直接访问"amount"字段,因为它存在于另一个类中。

{
    "status": "success",
    "status_code": "200",
    "data": [
        {
            "transaction_id": "2",
            "transaction_date": "2018-04-19 05:27:23.0",
            "amount": "200.00",
            "user_id": "2",
            "currency": "MXN",
            "associate_id": "1",
            "associate": {
                "is_active": "N",
                "associate_type": "Autoservicio",
                "name": "alsuper",
                "created_date": "12-Feb-2018 07:31:58 AM",
                "associate_id": "1",
                "url": null,
                "last_update_date": "12-Feb-2018 07:31:58 AM"
            },
            "card_id": "2",
            "card": {
                "bank_code": "002",
                "is_active": "Y",
                "allows_charges": "Y",
                "card_number": "411111XXXXXX1111",
                "openpay_card_id": "kiusphu8moqri6qys7sg",
                "type": "debit",
                "card_id": "2",
                "expiration_year": "21",
                "user_id": "2",
                "expiration_month": "10",
                "bank_name": "bank name",
                "created_date": "21-Mar-2018 05:46:58 AM",
                "brand": "visa",
                "last_update_date": "21-Mar-2018 05:46:58 AM",
                "holder_name": "name name name name"
            }
        }
   ]
}

我很高兴分享适配器类,现在我不分享是因为我想对这个问题有一些新的认识。

更新1

因此,在应用Raja Jawahar的解决方案后,我能够运行一次,但是在进行了最终更改之后,出现了以下情况。

D/1: Loaded View
D/2: Loaded recycler View
I/art: Do partial code cache collection, code=22KB, data=30KB
       After code cache collection, code=22KB, data=30KB
       Increasing code cache capacity to 128KB
D/OkHttp: --> GET http://URL http/1.1
          --> END GET
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException:  (No such file or directory)
W/ImageView: resolveUri failed on bad bitmap uri: 
D/OkHttp: <-- 200  http:URL (757ms)
          Access-Control-Allow-Origin: *
          Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With
          Content-Type: application/json
          Content-Length: 4109
D/OkHttp: Date: Sun, 15 Jul 2018 13:42:20 GMT
D/OkHttp: {"status":"success","status_code":"200","data": DATA]}
          <-- END HTTP (4109-byte body)
D/6: Passing to Adapter Failure
     java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我的支持代码如下,

片段

TransactionAssociate = new ArrayList<>();
        recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        transactionsAdapter = new TransactionsAdapter(getContext(), TransactionAssociate);
        recyclerView.setAdapter(transactionsAdapter);
        Log.d("2", "Loaded recycler View");
        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call<List<Transactions>> call = apiInterface.getTransactionList(sharedPreferences.getString(UNIQUE_ID, "qwe"));
        call.enqueue(new Callback<List<Transactions>>() {
            @Override
            public void onResponse(Call<List<Transactions>> call, Response<List<Transactions>> response) {

                TransactionAssociate = response.body();
                Log.d("5", "Passing to Adapter");
                try {
                    transactionsAdapter.setTransactionsList(TransactionAssociate);
                    Log.d("4", "Passed to Adapter");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<List<Transactions>> call, Throwable t) {
                Log.d("6", "Passing to Adapter Failure", t);
            }
        });

Http接口

@GET("URL")
Call<List<Transactions>>getTransactionList(@Path(value = "user_id",encoded = true)String user_id);

适配器

public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.MyViewHolder>{
    private Context context;
    private List <Transactions> TransactionsList;


    public TransactionsAdapter(Context context, List<Transactions> TransactionsList) {
        this.context = context;
        this.TransactionsList = TransactionsList;
    }

    public void setTransactionsList(List<Transactions> transactionsList){
        this.TransactionsList = transactionsList;

        notifyDataSetChanged();
    }

    @Override
    public TransactionsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    }

    @Override
    public void onBindViewHolder(TransactionsAdapter.MyViewHolder holder, int position) {
        Transactions transactionsList = TransactionsList.get(position);
        Transactions.DataEntity dataEntity = transactionsList.getData().get(0);
        holder.associateName.setText(dataEntity.getAssociate().getName());
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{

        public MyViewHolder(View itemView) {
            super(itemView);
        }
    }
}

Transactions.class

public class Transactions {

@SerializedName("data")
private List<DataEntity> data;
@SerializedName("status_code")
private String statusCode;
@SerializedName("status")
private String status;

public List<DataEntity> getData() {
    return data;
}

public void setData(List<DataEntity> data) {
    this.data = data;
}

public String getStatusCode() {
    return statusCode;
}

public void setStatusCode(String statusCode) {
    this.statusCode = statusCode;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public static class DataEntity {
    @SerializedName("card")
    private CardEntity card;
    @SerializedName("card_id")
    private String cardId;
    @SerializedName("associate")
    private AssociateEntity associate;
    @SerializedName("associate_id")
    private String associateId;
    @SerializedName("currency")
    private String currency;
    @SerializedName("user_id")
    private String userId;
    @SerializedName("amount")
    private String amount;
    @SerializedName("transaction_date")
    private String transactionDate;
    @SerializedName("transaction_id")
    private String transactionId;
}

public static class CardEntity {
    @SerializedName("holder_name")
    private String holderName;
    @SerializedName("last_update_date")
    private String lastUpdateDate;
    @SerializedName("brand")
    private String brand;
    @SerializedName("created_date")
    private String createdDate;
    @SerializedName("bank_name")
    private String bankName;
    @SerializedName("expiration_month")
    private String expirationMonth;
    @SerializedName("user_id")
    private String userId;
    @SerializedName("expiration_year")
    private String expirationYear;
    @SerializedName("card_id")
    private String cardId;
    @SerializedName("type")
    private String type;
    @SerializedName("openpay_card_id")
    private String openpayCardId;
    @SerializedName("card_number")
    private String cardNumber;
    @SerializedName("allows_charges")
    private String allowsCharges;
    @SerializedName("is_active")
    private String isActive;
    @SerializedName("bank_code")
    private String bankCode;
}

public static class AssociateEntity {
    @SerializedName("last_update_date")
    private String lastUpdateDate;
    @SerializedName("associate_id")
    private String associateId;
    @SerializedName("created_date")
    private String createdDate;
    @SerializedName("name")
    private String name;
    @SerializedName("associate_type")
    private String associateType;
    @SerializedName("is_active")
    private String isActive;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

}

1 个答案:

答案 0 :(得分:2)

使用DTO生成器(Android插件创建模型类)

为响应创建一个如下所示的类

public class DataModel {

  @SerializedName("data")   private List<Data> data;   @SerializedName("status_code")   private String status_code;   @SerializedName("status")   private String status;
     public static class Data {
    @SerializedName("card")
    private Card card;
    @SerializedName("card_id")
    private String card_id;
    @SerializedName("associate")
    private Associate associate;
    @SerializedName("associate_id")
    private String associate_id;
    @SerializedName("currency")
    private String currency;
    @SerializedName("user_id")
    private String user_id;
    @SerializedName("amount")
    private String amount;
    @SerializedName("transaction_date")
    private String transaction_date;
    @SerializedName("transaction_id")
    private String transaction_id;   }

  public static class Card {
    @SerializedName("holder_name")
    private String holder_name;
    @SerializedName("last_update_date")
    private String last_update_date;
    @SerializedName("brand")
    private String brand;
    @SerializedName("created_date")
    private String created_date;
    @SerializedName("bank_name")
    private String bank_name;
    @SerializedName("expiration_month")
    private String expiration_month;
    @SerializedName("user_id")
    private String user_id;
    @SerializedName("expiration_year")
    private String expiration_year;
    @SerializedName("card_id")
    private String card_id;
    @SerializedName("type")
    private String type;
    @SerializedName("openpay_card_id")
    private String openpay_card_id;
    @SerializedName("card_number")
    private String card_number;
    @SerializedName("allows_charges")
    private String allows_charges;
    @SerializedName("is_active")
    private String is_active;
    @SerializedName("bank_code")
    private String bank_code;   }

  public static class Associate {
    @SerializedName("last_update_date")
    private String last_update_date;
    @SerializedName("associate_id")
    private String associate_id;
    @SerializedName("created_date")
    private String created_date;
    @SerializedName("name")
    private String name;
    @SerializedName("associate_type")
    private String associate_type;
    @SerializedName("is_active")
    private String is_active;   } }

如下所示访问适配器中的数据模型

package com.mobieadz.sales;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

public class MyRecylerViewAdapter extends RecyclerView.Adapter<MyRecylerViewAdapter.MyViewHolder> {

  private Context context;
  private List<Data> datas = new ArrayList<>();

  @NonNull @Override
  public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
      int viewType) {
    return null;
  }

  public MyRecylerViewAdapter(Context context, List<DataModel> dataModels) {
    this.context = context;
    this.dataModels = dataModels;
  }

  @Override
  public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

   Data data = datas.get(position);
    youtextView.setText(data.amount);
    yourtextView.setText(data.associate.name)
    yourtextView.setText(data.associate.name)

  }

  @Override public int getItemCount() {
return dataModels.size();
  }

  public class MyViewHolder extends RecyclerView.ViewHolder {

    public MyViewHolder(View itemView) {
      super(itemView);
    }
  }
}