Анализ на JSON с Volley и GSON

Опитвам се да анализирам json от този url

http://api.openweathermap.org/data/2.5/forecast/daily?q=09100&mode=json&units=metric&cnt=7&lang=tr

Създадох pojo за gson и добавих базиран на залпове клас в моето приложение.

Искам да анализирам json обекти в моя списък с моя персонализиран адаптер

моята заявка Volley+Gson:

  private void loadAPI(){
        mRequestQueue = Volley.newRequestQueue(getActivity());

        String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=09100&mode=json&units=metric&cnt=7&lang=tr";
        //showDialog();
        GsonRequest<WeatherItem> myReq = new GsonRequest<WeatherItem>(
                Request.Method.GET,
                url,
                WeatherItem.class,
                mOnWeatherResponseLister(),
                mOnErrorListener());


        mRequestQueue.add(myReq);

    }

    private Response.Listener<WeatherItem> mOnWeatherResponseLister() {
  ForecastFragment 108 =  return new Response.Listener<WeatherItem>() {
            @Override
            public void onResponse(WeatherItem response) {
                try {
                    Log.d("Json Response", response.list.toString());
                    Log.d("Json Response", response.list.get(0).dt.toString());
                    Log.d("Json Response", response.list.get(0).weather.get(0).description.toString());
                    Log.d("Json Response",WeatherUtility.formatMinTemperature(getActivity(),response.list.get(0).temp.min));
                    for (int i = 0; i<=response.list.size()-1 ; i++) {


                        WeatherResp weatherResp = new WeatherResp();
                        Weather weather= new Weather();
                          weatherResp.weather.set(i,weather).setIcon(WeatherUtility.getIconResourceForWeatherCondition(response.list.get(i).weather.get(i).id));
                Fragment 121 = weatherResp.setDt((response.list.get(i).dt));
                          weatherResp.weather.set(i,weather).setDescription(response.list.get(i).weather.get(i).description.toString());
                          weatherResp.temp.setMin(Double.valueOf(WeatherUtility.formatMinTemperature(getActivity(), response.list.get(i).temp.min)));
                          weatherResp.temp.setMax(Double.valueOf(WeatherUtility.formatMaxTemperature(getActivity(), response.list.get(i).temp.max)));

                        arrItemList.add(weatherResp);
                    }

                    mListView.setAdapter(mForecastAdapter);
                    mForecastAdapter.notifyDataSetChanged();


                } catch (Exception e) {
                    e.printStackTrace();
                }
                //hideDialog();
            }

            ;
        };
    }

Похос:

public class WeatherItem {

    public String cod;
    public String message;
    public int cnt;
    public ArrayList<WeatherResp> list;
    public String getCod() {
        return cod;
    }

public class WeatherResp {

    public Long dt;
    public Temp temp;
    public Float pressure;
    public Integer humidity;
    public ArrayList<Weather> weather;
    public Float speed;
    public Float deg;
    public Integer clouds;

public class Weather {

    public Integer id;
    public String main;
    public String description;
    public int icon;
public class Temp {


    public Float day;
    public Double min;
    public Double max;
    public Double night;
    public Double eve;
    public Double morn;

Моят адаптер:

public class WeatherAdapter extends BaseAdapter {


private Context ctx;
private ArrayList<WeatherItem> weatherItems;
private ArrayList<WeatherResp> arrItemList;

public WeatherAdapter(Context ctx, ArrayList<WeatherResp> weatherResps) {

    this.ctx = ctx;
    this.arrItemList = weatherResps;
}

public static class ViewHolder {
    public ImageView iconView;
    public TextView dateView;
    public TextView descriptionView;
    public TextView highTempView;
    public TextView lowTempView;
    //public TextView humidity;
    //public TextView pressure;


    public ViewHolder(View v) {
        iconView = (ImageView) v.findViewById(R.id.list_item_icon);
        dateView = (TextView) v.findViewById(R.id.list_item_date_textview);
        descriptionView = (TextView) v.findViewById(R.id.list_item_forecast_textview);
        highTempView = (TextView) v.findViewById(R.id.list_item_high_textview);
        lowTempView = (TextView) v.findViewById(R.id.list_item_low_textview);

        v.setTag(this);
    }
}

/**
 * Cache of the children views for a forecast list item.
 */
@Override
public int getCount() {
    return weatherItems.size();

}

@Override
public Object getItem(int i) {
    return weatherItems.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int position, View convertview, ViewGroup viewGroup) {

    ViewHolder holder;
    View v = convertview;

    if (v == null) {
        v = View.inflate(ctx, R.layout.list_items_forecast, viewGroup);
        holder = new ViewHolder(v);
        holder.iconView = (ImageView) v.findViewById(R.id.list_item_icon);
        holder.dateView = (TextView) v.findViewById(R.id.list_item_date_textview);
        holder.descriptionView = (TextView) v.findViewById(R.id.list_item_forecast_textview);
        holder.lowTempView = (TextView) v.findViewById(R.id.list_item_low_textview);
        holder.highTempView = (TextView) v.findViewById(R.id.list_item_high_textview);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }

    WeatherResp weatherResp1 = arrItemList.get(position);

    holder.iconView.setImageResource(weatherResp1.getWeather().get(position).getIcon());
    holder.dateView.setText(weatherResp1.getDt().toString());
    holder.descriptionView.setText(weatherResp1.getWeather().get(position).getDescription());
    holder.lowTempView.setText(WeatherUtility.formatMinTemperature(ctx, weatherResp1.getTemp().min));
    holder.highTempView.setText(WeatherUtility.formatMaxTemperature(ctx,weatherResp1.getTemp().max));
    return v;
}

Когато стартирам моя logcat е:

W/System.err﹕ java.lang.NullPointerException
W/System.err﹕ at com.hasan.basan.fragment.ForecastFragment$1.onResponse(ForecastFragment.java:121)
W/System.err﹕ at com.hasan.basanfragment.ForecastFragment$1.onResponse(ForecastFragment.java:108)
W/System.err﹕ at com.hasan.basan.utility.GsonRequest.deliverResponse(GsonRequest.java:78)
W/System.err﹕ at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:725)
W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5041)
W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

Къде ми е грешката? Благодаря предварително


person Hasan Basan    schedule 07.12.2014    source източник
comment
Разгледайте този отговор -› stackoverflow.com/a/31386256/1177959   -  person Sotti    schedule 13.07.2015


Отговори (1)


Вашето изключение се хвърля от тук: com.hasan.basan.fragment.ForecastFragment$1.onResponse(ForecastFragment.java:121) Не мога да видя номерата на редовете, така че ще се опитам да отгатна защо е хвърлено изключението.

WeatherResp weatherResp = new WeatherResp();
Weather weather= new Weather();
weatherResp.weather.set(i,weather).setIcon(WeatherUtility.getIconResourceForWeatherCondition(response.list.get(i).weather.get(i).id));

На 3-ти ред от код имате достъп до varialbe weatherResp.weather. Имам 2 обяснения.

  1. Може би сте забравили да зададете нов екземпляр Weather на вашата променлива weatherResp.

  2. Може би сте забравили да инициализирате ArrayList от Weather променливи в конструктора по подразбиране на WeatherResp клас.

person Anatol    schedule 07.12.2014
comment
Промених Weather като този публичен клас Weather extends ArrayList‹Weather› { и добавих конструктор към WeatherResp public WeatherResp(ArrayList‹Weather› weather) { this.weather = weather; } - person Hasan Basan; 07.12.2014
comment
NPE изчезна, но списъкът ми не се попълни :( - person Hasan Basan; 07.12.2014
comment
когато отстранявам грешки arrItemList = {java.util.ArrayList@3462362} size=0 Мисля, че трябва да се попълни с променливи weatherResp. - person Hasan Basan; 07.12.2014
comment
@HasanBasan намери ли тогава коя променлива е нула? - person Anatol; 07.12.2014
comment
Имам 4 моделни класа и искам да попълня моя списък с масиви с екземпляр на WeatherResp. - person Hasan Basan; 07.12.2014