在一个cardview中显示来自不同URL的已解析json数据。 (已编辑)

时间:2018-12-01 19:33:51

标签: android json android-volley indexoutofboundsexception

首先,我使用parley来解析parseJsonTour()方法以接收json数据。并使用我从parseJsontour()收到的数据mapx调用parseJsonWeather()方法。

private void parseJsonTour() {
    double lat = gps.getLatitude();
    String mapY = Double.toString(lat);
    Log.v("mapY", mapY);
    double lon = gps.getLongitude();
    String mapX = Double.toString(lon);
    Log.v("mapX", mapX);

    String url = "http://api.visitkorea.or.kr/openapi/service/rest/KorService/locationBasedList?" +
            "serviceKey=gCoROJjTpFwTjV%2F%2BoWBcWMdj0z%2Fxsu22eY19j%2FoeNSJOnrkaPehhoyIzp%2FrtMkNYAzVlBFzmnI6cCsKODNmejA%3D%3D" +
            "&numOfRows=10&pageSize=50&pageNo=1&startPage=1&MobileOS=AND&MobileApp=WelcomeToSeoul&arrange=A&mapX=" + mapX + "&mapY=" + mapY + "&radius=3000&listYN=Y&_type=json";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONObject parseResponse = response.getJSONObject("response");
                        JSONObject parseBody = parseResponse.getJSONObject("body");
                        JSONObject parseItems = parseBody.getJSONObject("items");
                        JSONArray parseItem = parseItems.getJSONArray("item");


                        for (int i = 0; i < parseItem.length(); i++) {
                            JSONObject item = parseItem.getJSONObject(i);


                            if (item.has("firstimage")) {
                                String imageUrl = item.getString("firstimage");
                                String tourname = item.getString("title");
                                String contentId = item.getString("contentid");
                                String mapX = item.getString("mapx");
                                String mapY = item.getString("mapy");
                                double mapx = Double.parseDouble(mapX);
                                double mapy = Double.parseDouble(mapY);
                                parseJsonWeather(mapy, mapx);
                                mTourList.add(new TourItem(imageUrl, tourname, mapX, mapY, contentId));
                            }
                        }
                        mTourAdapter = new TourAdapter(HomeActivity.this, mTourList, mWeatherList);
                        mRecyclerView.setAdapter(mTourAdapter);
                        mTourAdapter.setOnItemClickListener(HomeActivity.this);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mRequestQueue.add(request);
}

private void parseJsonWeather(double X, double Y) {
    String today = getToday();
    String basetime = getBaseTime();
    LatXLngY tmp = convertGRID_GPS(TO_GRID, X, Y);
    int nx = Integer.parseInt(String.valueOf(Math.round(tmp.x)));
    int ny = Integer.parseInt(String.valueOf(Math.round(tmp.y)));
    String gridX = Integer.toString(nx);
    Log.v("gridX",gridX);
    String gridY = Integer.toString(ny);
    Log.v("gridy", gridY);
    Log.v("today", today);
    Log.v("basetime", basetime);

    String url = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastGrib?" +
            "serviceKey=gCoROJjTpFwTjV%2F%2BoWBcWMdj0z%2Fxsu22eY19j%2FoeNSJOnrkaPehhoyIzp%2FrtMkNYAzVlBFzmnI6cCsKODNmejA%3D%3D&" +
            "base_date=" + today + "&base_time=" + basetime + "&nx=" + gridX + "&ny=" + gridY + "&numOfRows=10&pageSize=10&pageNo=1&startPage=1&_type=json";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse (JSONObject response) {
                    try {
                        JSONObject parseResponse = response.getJSONObject("response");
                        JSONObject parseBody = parseResponse.getJSONObject("body");
                        JSONObject parseItems = parseBody.getJSONObject("items");
                        JSONArray parseItem = parseItems.getJSONArray("item");

                        JSONObject item0 = parseItem.getJSONObject(0);
                        String rainform = item0.getString("obsrValue");
                        Log.v("rainform", rainform);
                        JSONObject item1 = parseItem.getJSONObject(3);
                        String temp = item1.getString("obsrValue");
                        Log.v("temp", temp);

                        mWeatherList.add(new WeatherItem(rainform, temp));


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


                }
            }, new Response.ErrorListener() {
        @Override

        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    mRequestQueue.add(request);

}

然后我用两个Arraylist(mTourList,mWeatherList)制作了适配器,如下代码。

mTourAdapter = new TourAdapter(HomeActivity.this, mTourList, mWeatherList);
                        mRecyclerView.setAdapter(mTourAdapter);

并编辑了这样的游览适配器代码。

public class TourAdapter extends RecyclerView.Adapter<TourAdapter.TourViewHolder> {

private Context mContext;
private ArrayList<TourItem> mTourList;
private ArrayList<WeatherItem> mWeatherList;
private OnItemClickListener mListener;

public interface  OnItemClickListener {
    void onItemClick(int position);
}


public void setOnItemClickListener(OnItemClickListener listener)
{ mListener = listener; }

public TourAdapter(Context context, ArrayList<TourItem> tourlist, ArrayList<WeatherItem> weatherlist){
    mContext = context;
    mTourList = tourlist;
    mWeatherList = weatherlist;
}

@NonNull
@Override
public TourViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.tour_item, parent,false);
    return new TourViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull TourViewHolder holder, int position) {
    TourItem currentItem1 = mTourList.get(position);
    WeatherItem currentItem2 = mWeatherList.get(position);

    String imageUrl = currentItem1.getImageUrl();
    String tourName = currentItem1.getTourname();
    String mapX = currentItem1.getMapX();
    String mapY = currentItem1.getMapY();
    String contentId = currentItem1.getContentId();
    String temp = currentItem2.getTemp();
    String rainform = currentItem2.getRainform();

    holder.mTextViewTemp.setText(temp + "˚C");
    holder.mTextViewTourname.setText(tourName);
    Glide.with(mContext).load(imageUrl).into(holder.mImageView);


}

@Override
public int getItemCount() {
    return mTourList.size() + mWeatherList.size();
}

public class TourViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImageView;
    public ImageView mImageViewWicon;
    public TextView mTextViewTourname;
    public TextView mTextViewTemp;

    public TourViewHolder(View itemView) {
        super(itemView);
        mImageView = itemView.findViewById(R.id.image_view);
        mTextViewTourname = itemView.findViewById(R.id.text_view_name);
        mImageViewWicon = itemView.findViewById(R.id.image_weather_icon);
        mTextViewTemp = itemView.findViewById(R.id.temp);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    int position = getAdapterPosition();
                    if(position != RecyclerView.NO_POSITION) {
                        mListener.onItemClick(position);
                    }
                }
            }
        });
    }
}

有时它似乎可以工作,但是大多数情况下都发生了java.lang.IndexOutOfBoundsException:索引:0,大小:0。我认为onBindViewHolder()中存在问题,但我不知道如何处理。如果有人知道此问题,请帮助我。谢谢。

0 个答案:

没有答案