解析JSON url后,ArrayList似乎是空的

时间:2016-02-10 16:24:08

标签: android json android-recyclerview android-volley

我是Android开发的新手,但我正在尝试从stackoverflow中有经验的用户那里学到很多东西。

我正在进行一个小项目,因为某些原因我完全被阻止了

我遇到的问题是,当我解析json url并使用android-volley lib成功创建带有对象的photosList数组时,当我将参数photosList传递给myPhotosAdapter时,我最终出于某种原因使用空数组( ).... :( 见吼声

mAdapter = new MyPhotosAdapter(photosList);

My Fragment Class

public class MyDetailFragment extends Fragment {

// Log tag
private static final String TAG = MyDetailFragment.class.getSimpleName();
public static final String ARG_ITEM_ID = "item_id";
protected RecyclerView mRecyclerView;
protected MyPhotosAdapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
protected LayoutManagerType mCurrentLayoutManagerType;
private List<Photo> photosList = new ArrayList<Photo>();

//empty constructor
public MyDetailFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments().containsKey(ARG_ITEM_ID)) {

        Activity activity = this.getActivity();
        CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
        if (appBarLayout != null) {
            appBarLayout.setTitle("ID " + getArguments().getString(ARG_ITEM_ID));
        }
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    //set the url for the got get the photos
    String url = AppConstants.DETAILS_PHOTOS_URL + getArguments().getString(ARG_ITEM_ID);                    

    View rootView = inflater.inflate(R.layout.main_detail, container, false);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view_photos);
    mAdapter = new MyPhotosAdapter(photosList);
    mRecyclerView.setAdapter(mAdapter);
    mLayoutManager = new GridLayoutManager(getActivity(),2);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // Creating volley request 
    JsonArrayRequest photosReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject obj = response.getJSONObject(i);
                            Photo p = new Photo();
                            p.setPhotoUrl(obj.getString("photo_url"));
                            // adding photo to photos array
                            photosList.add(p);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getActivity(),
                                    getString(R.string.msg_unknown_error),
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    //mAdapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getActivity(),
                    getString(R.string.msg_fetch_photos_error),
                    Toast.LENGTH_LONG).show();
        }
    });

    AppController.getInstance().addToRequestQueue(photosReq);

    return rootView;
}
}

我的模特课

public class Photo {
private String photoUrl;

public Photo() {
}

public Photo(String photoUrl) {
    this.photoUrl = photoUrl;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}
}

和我的Adapter类

public class MyPhotosAdapter extends RecyclerView.Adapter<MyPhotosAdapter.MyViewHolder> {

ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private List<Photo> photosList;

public MyPhotosAdapter(List<Photo> photosList) {
    this.photosList = photosList;
}

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

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Photo p = photosList.get(position);
    holder.photo_thumbnail.setImageUrl(p.getPhotoUrl(), imageLoader);
}

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    public NetworkImageView photo_thumbnail;

    public MyViewHolder(View itemView) {
        super(itemView);
        photo_thumbnail = (NetworkImageView) itemView.findViewById(R.id.photo_thumbnail);
    }
}
}

我的JSON网址返回

[
  {
      "photo_url": "http://api.xxxxxxxxxxxxxxx.com/images/1.jpg"
  },
  {
      "photo_url": "http://api.xxxxxxxxxxxxxxx.com/images/2.jpg"
  }
]

有人可以告诉我上面的代码有什么问题吗?我已经尝试了所有我能想到的东西,但仍然没有成功:( :(

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

你注释掉了

    mAdapter.notifyDataSetChanged();

或者你可以初始化

     mAdapter = new MyPhotosAdapter(photosList);

for (int i = 0; i < response.length(); i++) {
                    try {
                        ......
                    } catch (JSONException e) {
                        .....
                    }
                }
            mAdapter = new MyPhotosAdapter(photosList);
            mRecyclerView.setAdapter(mAdapter);

应该有用。谢谢