簡體   English   中英

我如何獲得清單 <Pojo1> 它存在於其根Pojo中,該Pojo也作為列表返回 <Pojo>

[英]How do I get List<Pojo1> which is present in its root Pojo, which also returns as a List<Pojo>

我正在解析一個Ola Cabs API,其響應如下:

{
  "categories": [
{
  "id": "mini",
  "display_name": "Mini",
  "currency": "INR",
  "distance_unit": "kilometre",
  "time_unit": "minute",
  "eta": 1,
  "distance": "0.2",
  "ride_later_enabled": "true",
  "image": "http://d1foexe15giopy.cloudfront.net/mini.png",
  "fare_breakup": [
    {
      "type": "flat_rate",
      "minimum_distance": "4",
      "minimum_time": "0",
      "base_fare": "80",
      "minimum_fare": "0",
      "cost_per_distance": "10",
      "waiting_cost_per_minute": "0",
      "ride_cost_per_minute": "1",
      "rates_higher_than_usual": false,
      "surcharge": []
    },
    {
      "type": "airport_rate",
      "minimum_distance": "25",
      "minimum_time": "0",
      "base_fare": "499",
      "minimum_fare": "0",
      "cost_per_distance": "13",
      "waiting_cost_per_minute": "0",
      "ride_cost_per_minute": "1",
      "rates_higher_than_usual": false,
      "surcharge": []
    }
  ],
  "cancellation_policy": {
    "cancellation_charge": 50,
    "currency": "INR",
    "cancellation_charge_applies_after_time": 5,
    "time_unit": "minute"
  }
}
],
"ride_estimate": {}
}

我將Model類創建為:

public class ListOfEstimateTimeForOla() {
List<Categories> categories;
//getter of categories
}

上課是我收到所有答復的主要POJO。 下面給出的是另一個POJO,名為-Categories。

public class Categories() {
List<Fare_breakup>;
//getter of Fare_breakup

}

還有一個定義為Fare_breakup的模型,如下所示:

  public class Fare_breakup {
   int base_fare;
    //getter of fare

  }

現在,我在片段中得到響應,其代碼如下:

requestInterface = retrofit.create(RideRequestInterface.class);
        if (pickup_lat != 0 && pickup_long != 0 ) {
            Call<ListOfEstimateTimeForOla> priceData = requestInterface.getEstimateTimeForOla(pickup_lat, pickup_long);
            priceData.enqueue(new Callback<ListOfEstimateTimeForOla>() {
                @Override
                public void onResponse(@NonNull Call<ListOfEstimateTimeForOla> call, @NonNull Response<ListOfEstimateTimeForOla> response) {
                    int statusCode = response.code();

                    ListOfEstimateTimeForOla data = response.body();

                    assert data != null;

                    EstimateTimeAdapterForOla adapter = new EstimateTimeAdapterForOla(data.getCategories(), getContext());
                    estimatePriceForOla.setAdapter(adapter);

                    progressForOla.setVisibility(View.GONE);
                    estimatePriceForOla.setVisibility(View.VISIBLE);
                    Log.d("Estimated Time for Ola", "onResponse: "+ statusCode);
                }

                @Override
                public void onFailure(@NonNull Call<ListOfEstimateTimeForOla> call, @NonNull Throwable t) {
                    Log.d("Estimated Time for Ola", "onResponse: "+ t.getMessage());
                }
            });
        }

我需要在適配器類別如下的RecyclerView中獲取票價:

public class EstimateTimeAdapterForOla extends RecyclerView.Adapter<EstimateTimeAdapterForOla.EstimateTimeHolder>{

private Context c;
private List<EstimateTimeForOla> estimateTimeForOla;

public EstimateTimeAdapterForOla (List<EstimateTimeForOla> estimateTimeForOla, Context c) {
    this.estimateTimeForOla = estimateTimeForOla;
    this.c = c;
}

@Override
public EstimateTimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.estimate_time_for_ola, parent, false);
    EstimateTimeHolder holder = new EstimateTimeHolder(view);
    return holder;
}

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

    holder.displayName.setText(estimateTimeForOla.get(position).getDisplay_name());
    Picasso.with(c).load(estimateTimeForOla.get(position).getImage()).into(holder.displayIcon);
    holder.fare.setText(String.valueOf(estimateTimeForOla.get(position).getFare_breakup().get(0).getBase_fare()));
    holder.eta.setText(String.valueOf(estimateTimeForOla.get(position).getEta()));
}

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

public static class EstimateTimeHolder extends RecyclerView.ViewHolder {

    TextView displayName, fare, eta;
    ImageView displayIcon;

    public EstimateTimeHolder(View itemView) {
        super(itemView);

        displayName = itemView.findViewById(R.id.display_name_ola_tv);
        fare = itemView.findViewById(R.id.actual_fare_tv);
        eta = itemView.findViewById(R.id.actual_eta_tv);
        displayIcon = itemView.findViewById(R.id.display_icon_ola_iv);
    }
}
}

現在,我的問題是如何通過onBindViewHolder在recyclerview中獲取票價?

下面給出的是運行以上代碼后的錯誤:

07-28 17:27:50.134 330-330/test.android.mobond.tabs.slidingtabs E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: test.android.mobond.tabs.slidingtabs, PID: 330
                                                                              java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
                                                                                  at test.android.mobond.tabs.slidingtabs.adapters.EstimateTimeAdapterForOla.onBindViewHolder(EstimateTimeAdapterForOla.java:45)
                                                                                  at test.android.mobond.tabs.slidingtabs.adapters.EstimateTimeAdapterForOla.onBindViewHolder(EstimateTimeAdapterForOla.java:22)
                                                                                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6400)
                                                                                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6433)
                                                                                  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5377)
                                                                                  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5640)
                                                                                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5482)
                                                                                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5478)
                                                                                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2215)
                                                                                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1542)
                                                                                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1502)
                                                                                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
                                                                                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3625)
                                                                                  at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3067)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1629)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                                                                                  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5908)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:3076)
                                                                                  at android.view.View.measure(View.java:18870)
                                                                                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2392)
                                                                                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1416)
                                                                                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1661)
                                                                                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1301)
                                                                                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7016)
                                                                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
                                                                                  at android.view.Choreographer.doCallbacks(Choreographer.java:590)
                                                                                at android.view.Choreog

使用JSON2POJO創建POJO以創建足夠的POJO類並使用Retrofit

我用它來獲取天氣的詳細信息。 此示例是獲取數據的完全不同的方法。 我認為這可能對您有用。

private static JSONObject getObject(String tagName, JSONObject jObj) throws JSONException {
    JSONObject subObj = jObj.getJSONObject(tagName);
    return subObj;
}

private static JSONArray getArray(String tagName, JSONObject jObj) throws JSONException {
    JSONArray subObj = jObj.getJSONArray(tagName);
    return subObj;
}

private static String getString(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getString(tagName);
}

private static float getFloat(String tagName, JSONObject jObj) throws JSONException {
    return (float) jObj.getDouble(tagName);
}

private static int getInt(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getInt(tagName);
}


//weatherMethod
private void getWeather(String city){

    String url = String.format(EndPoints.getWeather, city);
    pd.show();

    JsonRequest req = new JsonRequest(Request.Method.GET, url, null, new com.android.volley.Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            if (pd != null) pd.cancel();

            try {
                Timber.d("find Weather : %s", response.toString() + " ID - "+response.get("id"));

                try {
                    JSONObject coordObj = getObject("coord", response);
                    Log.d("TAG"," lat "+getFloat("lat", coordObj));
                    Log.d("TAG"," lon "+getFloat("lon", coordObj));

                    JSONObject sysObj = getObject("sys", response);
                    Log.d("TAG"," country "+getString("country", sysObj));
                    Log.d("TAG"," sunrise "+getInt("sunrise", sysObj));
                    Log.d("TAG"," sunset "+getInt("sunset", sysObj));
                    Log.d("TAG"," name "+getString("name", response));

                    JSONObject mainObj = getObject("main", response);
                    Log.d("TAG"," temp "+getFloat("temp", mainObj));
                    Log.d("TAG"," pressure "+getInt("pressure", mainObj));
                    Log.d("TAG"," humidity "+getInt("humidity", mainObj));

                    JSONArray weatherArray = getArray("weather", response);
                    JSONObject weatherObj = weatherArray.getJSONObject(0);
                    //JSONObject weatherObj = getObject("main", weatherArray.getJSONObject(0));

                    Log.d("TAG"," main "+getString("main", weatherObj));
                    Log.d("TAG"," description "+getString("description", weatherObj));
                    Log.d("TAG"," ***- icon -*** "+getString("icon", weatherObj));
                    //"http://openweathermap.org/img/w/"+getString("icon", weatherObj)+".png";

                    JSONObject cloudsObj = getObject("clouds", response);
                    Log.d("TAG"," all "+getInt("all", cloudsObj));

                    JSONObject windObj = getObject("wind", response);
                    Log.d("TAG"," speed "+getFloat("speed", windObj));
                    Log.d("TAG"," deg "+getInt("deg", windObj));

                    description = getString("description", weatherObj);
                    lastUpdate =  getString("dt", response);
                    humidity =  getInt("humidity", mainObj);
                    clouds =  getInt("all", cloudsObj);
                    temperature = String.valueOf(getFloat("temp", mainObj));
                    pressure = String.valueOf(getInt("pressure", mainObj));
                    wind =  getString("speed", windObj);
                    sunrise = String.valueOf(getInt("sunrise", sysObj));
                    sunset = String.valueOf(getInt("sunset", sysObj));

                    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(getString("name", response));

                    preLoadWeather();

                    //weather.location = loc;
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (pd != null) pd.cancel();
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    });
    req.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    req.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(req, "weather_requests");

}

/*

    {"coord":{"lon":78.47,"lat":17.38},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],
    "base":"stations","main":{"temp":306.15,"pressure":1006,"humidity":63,"temp_min":306.15,"temp_max":306.15},
    "visibility":6000,"wind":{"speed":4.1,"deg":280},"clouds":{"all":40},"dt":1498132800,
    "sys":{"type":1,"id":7830,"message":0.0163,"country":"IN","sunrise":1498090389,"sunset":1498137799},
    "id":1269843,"name":"Hyderabad","cod":200}

* */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM