2017-07-28 2 views
0

Je l'analyse d'une API Cabs Ola dont la réponse vient comme ceci:Comment puis-je obtenir la liste <Pojo1> qui est présent dans sa Pojo racine, qui renvoie également une liste <Pojo>

{ 
    "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": {} 
} 

J'ai créé le modèle classes comme:

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

Au-dessus de la classe est le POJO principal où j'obtiens toute la réponse. Ci-dessous donné un autre POJO nommé - Catégories.

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

} 

et il y a un modèle défini comme Fare_breakup qui est comme ceci:

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

    } 

Maintenant, je reçois la réponse dans mon fragment, dont le code est comme ci-dessous:

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()); 
       } 
      }); 
     } 

I besoin d'obtenir le tarif dans mon RecyclerView dont la classe d'adaptateur est ci-dessous:

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); 
    } 
} 
} 

Maintenant, mon problème est comment obtenir le tarif dans mon recyclerview via onBindViewHolder?

Ci-dessous est donné l'erreur après l'exécution du code ci-dessus:

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 
+0

Est-ce que data.getCategories() vous renvoie la liste correcte? –

+0

Il n'y a pas de propriété appelée «tarif» dans votre json. – SripadRaj

+0

@AyushKhare, oui .. Il me renvoie la liste des catégories, qui contient la liste des Fare_breakup –

Répondre

1

Créer POJO en utilisant JSON2POJO pour créer des classes adéquates POJO et utiliser Rénovation

+0

J'ai créé les classes POJO, mais je n'ai pas pu récupérer le base_fare car il lance NPE. –

+0

Pouvez-vous partager le logcat de NPE? – SripadRaj

+0

J'ai édité le poste –

0

J'ai utilisé ce pour obtenir les détails météorologiques. Cet exemple est une approche complètement différente pour obtenir les données. Je pense que cela peut vous être utile.

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} 

* */