使用改进传递json数组

时间:2016-07-14 06:14:41

标签: android json retrofit2

我是android和retrofit的新手,我面临很多解析json数组的问题。我可以在我的logcat中打印json响应。它的工作正常。我只想在cardview中显示我的设备上的图像和数据。拜托,我一直在努力争取更多的时间。帮助我们。帮我处理我的代码。我不想放弃。

pojo class:

public class DetailData {
    public String image;
    public String pname;
    public String pprice;
    public String pdescr;

    public String getPdescr() {
        return pdescr;
    }

    public void setPdescr(String pdescr) {
        this.pdescr = pdescr;
    }

    public String getPprice() {
        return pprice;
    }

    public void setPprice(String pprice) {
        this.pprice = pprice;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

适配器类:

public class DetailsAdapter extends RecyclerView.Adapter<DetailsAdapter.usersViewHolder> {

    private ArrayList<DetailData> itemList;
    private Context context1;
    onclickListener mOnclickListener;

    public DetailsAdapter(Context context, ArrayList<DetailData> itemList) {
        this.itemList = itemList;
        this.context1 = context;
    }

    public void updatevalues(ArrayList<DetailData> newlist) {
        this.itemList = newlist;
        notifyDataSetChanged();

    }


    public class usersViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        @Bind(R.id.description)
        TextView pdescr;

        @Bind(R.id.image)
        ImageView image;

        @Bind(R.id.pprice)
        TextView pprice;

        @Bind(R.id.parent)
        RelativeLayout parent;

        public usersViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            parent.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.parent:
                    mOnclickListener.onCategoryClick(itemView, getAdapterPosition());
                    break;


                default:
                    break;
            }
        }
    }


    @Override
    public DetailsAdapter.usersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_detaillist, null);
        DetailsAdapter.usersViewHolder viewHolder = new DetailsAdapter.usersViewHolder(layoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(usersViewHolder holder, int position) {
        DetailData current = itemList.get(position);
        holder.pdescr.setText(current.getPdescr());
        holder.pprice.setText(current.getPprice());
       // holder.pdescr.setText(current.getPdescr());
    }


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


    public interface onclickListener {
        void onCategoryClick(View v, int position);
    }


    public void setOnItemClickListener(final onclickListener mItemClickListener) {
        this.mOnclickListener = mItemClickListener;
    }
}

活动类:

public class Test extends AppCompatActivity {
    Call<ResponseBody> call;
    DetailsAdapter rcAdapter;
    RecyclerView recyclerView;
    ArrayList<DetailData> adapterList = new ArrayList<>();
    LinearLayoutManager linearLayoutManager;


    private static final String JSON_BED = "http://localhost/shree_decor/jsonfetch.php";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cat_detail);
        Intent i = getIntent();
        int catid = i.getExtras().getInt("catid");
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        rcAdapter = new DetailsAdapter(Test.this, adapterList);
        linearLayoutManager = new LinearLayoutManager(Test.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(rcAdapter);
        recyclerView.setHasFixedSize(true);

        API service = ServiceGenerator.createService(API.class);
        call = service.getCategoriesData(String.valueOf(catid));

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String urlResponse = Utils.convertTypedBodyToString(response);
                JSONObject json = null;
                JSONArray jsonResponse = null;
                Log.i("CatResponse - ", "" + urlResponse);
                //Log.i("CatResponse - ", "" + json);




                //CHECK THIS!
                try {
                    json = new JSONObject(urlResponse);
                    //coverting arraylist to array
                    String[] stringArray = adapterList.toArray(new String[0]);
                    for (int i = 0; i < stringArray.length; i++) {
                        DetailData current = new DetailData();
                        current.setPname(stringArray[i]);
                        // current.setImage(img[i]);
                        adapterList.add(current);
                    }

                    //return adapterList;
                  } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                     jsonResponse = json.getJSONArray("result");
                    Log.i("Array", "" + jsonResponse);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //PASS THE JSON ARRAY ONLY
                ArrayList<DetailData> itemList = null;
                Context context1 = null;
                //Log.i("CatResponse1 - ", "" + json);

                adapterList = getData(jsonResponse);
                DetailsAdapter da = new DetailsAdapter(context1, itemList);
                da.updatevalues(adapterList);


            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i("RetroError - ", "" + t.getMessage());
            }
        });


    }


    public ArrayList<DetailData> getData(JSONArray details) {
        ArrayList<DetailData> data = new ArrayList<>();

        for (int i = 0; i < details.length(); i++) {
            DetailData current = new DetailData();
            try {
                current.setImage(details.getJSONObject(i).getString("image"));
                current.setPdescr(details.getJSONObject(i).getString("pdescr"));
                current.setPname(details.getJSONObject(i).getString("pname"));
                current.setPprice(details.getJSONObject(i).getString("pprice"));
                data.add(current);
            } catch (JSONException e) {
                 e.printStackTrace();
            }
        }
        return data;
    }
}

xml布局          

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>


</LinearLayout>


<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    card_view:cardCornerRadius="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/image"
            android:layout_height="match_parent"
            android:layout_width="wrap_content"></ImageView>
        <TextView
            android:id="@+id/description"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="18dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/pprice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


    </LinearLayout>
</android.support.v7.widget.CardView>

响应

{
    "result": [{
        "image": null,
        "pname": "Barshi Bed",
        "pprice": "20000",
        "pdescr": "Barshi bed Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }, {
        "image": null,
        "pname": "King bed nexa one",
        "pprice": "15000",
        "pdescr": "King bed nexa one Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }, {
        "image": null,
        "pname": "Royal Sofa",
        "pprice": "25000",
        "pdescr": "Royal Sofa Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }]
}

请帮助我!

1 个答案:

答案 0 :(得分:0)

首先创建一个名为MyResponse.java的模型类

public class MyResponse implements Serializable {

  @Expose @SerializedName("result")
  private ArrayList<DetailData> listData;


  public ArrayList<DetailData> getListData() {
    return listData;
  }

  public void setListData(ArrayList<DetailData> listData) {
    this.listData = listData;
  } 
}

然后在你的界面Api.java上改变调用getCategoriesData类型:

@FormUrlEncoded
@POST("")
Call<MyResponse> getCategoriesData(@Field("catid") String catid);

最后在您的Activity.class上:

  1. 更改通话类型:

    Call<MyResponse> call;
    
  2. 更改enque:

    call.enqueue(new Callback<MyResponse>() {
        @Override
        public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
            if (response.isSuccessful()) {
                String strBody = response.body().toString();
                Log.i("---- NEWS_REST_SERVICE response : " + strBody);
                MyResponse responsePojo = response.body();
                adapterList = responsePojo.getListData();
    
                rcAdapter = new DetailsAdapter(Test.this, adapterList);
    
                rcAdapter.notifyDataSetChanged();
            } else {
                Log.i("---- NEWS_REST_SERVICE error response");
                int sc = response.code();
                switch (sc) {
    
                }
            }
        }
    
        @Override
        public void onFailure(Call<MyResponse> call, Throwable t) {
            Log.i("RetroError - ", "" + t.getMessage());
        }
    });