【问题标题】:I need assistabce displaying json data correctly in my android application我需要帮助在我的 android 应用程序中正确显示 json 数据
【发布时间】:2021-08-08 16:08:02
【问题描述】:

您好,我需要一些帮助。我从新闻 api 获取 json 数据并试图填充回收站视图。我面临的挑战是它很好地获取 json,但是当我填充我的回收器视图时,它会一遍又一遍地从一个新闻源多次显示一个 json 对象,而不是显示来自不同新闻源的不同新闻。这是我获取数据的方法

public void fetchNewsData() {

        client = new OkHttpClient();
        final MediaType JSON
                = MediaType.get("application/json; charset=utf-8");
        request = new Request.Builder().url("https://newsapi.org/v1/sources?apiKey="+apiKey).get().build();
        client.newCall(request).enqueue(new Callback() {

            public Response intercept(Interceptor.Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                ResponseBody body = response.body();
                bodyString = body.string();
                MediaType contentType = body.contentType();
                Log.d("Response", bodyString);
                return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
            }

            //fetching json data well
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            } // transmission failure callback

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {


                final String string = response.body().string();
                Log.i("cheese", "onResponse: " + string);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Snackbar.make(v,string,Snackbar.LENGTH_LONG).show();

                        try {

                            NewsItem singleNewsItem = new NewsItem();
                            JSONObject main = new JSONObject(string);
                            JSONArray jsonArray = main.getJSONArray("sources");

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                Log.i("json fetched",jsonObject.toString());
                                singleNewsItem.setSourceName(jsonObject.getString("name"));
                                singleNewsItem.setDescription(jsonObject.getString("description"));
                                singleNewsItem.setUrl(jsonObject.getString("url"));
                                singleNewsItem.setCountry(jsonObject.getString("country"));
                                newsItems.add(singleNewsItem);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mAdapter = new MyAdapter(newsItems, LatestNews.this);
                        mRecyclerView.setAdapter(mAdapter);
                    }
        });
    }

这是我的回收器视图的适配器类

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

    private  List<NewsItem> newsItemList;
    private Context mContext;

    public MyAdapter(List itemList, Context context) {

        this.newsItemList = itemList;
        this.mContext = context;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);
        // Return a new view holder
        return new MyViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {

        holder.itemView.setTag(newsItemList.get(position));
        NewsItem item = newsItemList.get(position);
        holder.txtName.setText(item.getSourceName());
        holder.txtUrl.setText(item.getUrl());
        holder.txtDescription.setText(item.getDescription());
        holder.txtCattegory.setText(item.getCategory());
    }

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

    // View holder class whose objects represent each list item
    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView txtName;
        public TextView txtUrl;
        public TextView txtDescription;
        public TextView txtCattegory;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            txtName = itemView.findViewById(R.id.txtName);
            txtUrl = itemView.findViewById(R.id.txtUrl);
            txtDescription = itemView.findViewById(R.id.txtDescription);
            txtCattegory = itemView.findViewById(R.id.txtCattegory);

        }


        public void bindData(NewsItem dataModel, Context context,int i) {


         }

        }
    }

【问题讨论】:

    标签: android json okhttp


    【解决方案1】:

    您的singleNewsItem 必须在for loop 中构造

    您可以看到的新闻可能是最后一个,因为您在list 中添加了相同的singleNewsItem。这意味着您的列表元素引用相同的内存地址。

    【讨论】:

    • 非常感谢您的工作。非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多