【问题标题】:ArrayList seems to be empty after parsing JSON url解析 JSON url 后,ArrayList 似乎为空
【发布时间】:2023-04-09 20:00:02
【问题描述】:

我是 android 开发的新手,但我想从 stackoverflow 的有经验的用户那里学到很多东西。

我正在做一个小项目,但由于某种原因我完全被阻止了

我遇到的问题是,当我解析 json url 并使用 android-volley lib 成功创建带有对象的 photosList 数组时,当我将参数 photosList 传递给 myPhotosAdapter( ).... :( 见下文

mAdapter = new MyPhotosAdapter(photosList);

我的片段类

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

还有我的适配器类

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"
  }
]

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

提前感谢您的帮助。

【问题讨论】:

  • 您收到任何错误吗? JSON是什么样子的,你验证了吗?
  • 非常感谢到目前为止的回答。不幸的是,我没有收到任何错误..我将URL记录到控制台,例如从请求中获取的响应对象和try {}的for循环中的photosList数组,我得到了预期的值.. ..问题是,由于某种原因,当我尝试将它作为参数传递给我的适配器时,photosList 数组为空,url 返回以下 json [ { "photo_url": "apixxxx.com/1.jpg" }, { "photo_url": "apixxxx.com/2.jpg" } ]

标签: android json android-recyclerview android-volley


【解决方案1】:

你注释掉了

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

应该可以。谢谢

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多