【问题标题】:Items not displaying in RecyclerViewRecyclerView 中未显示的项目
【发布时间】:2019-09-09 20:13:02
【问题描述】:

这是我现在面临的一个奇怪问题。 在我的应用程序中,我从链接中的 JSON 文件中获取数据,然后使用 Volley 解析它。现在我想在似乎不起作用的 RecyclerView 上显示数据,我很确定我的代码很好,但有些东西似乎不起作用,我找不到它。

activity_home.xml

这似乎在我用背景颜色测试时呈现:

<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activities.HomeActivity">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_main_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
        </androidx.recyclerview.widget.RecyclerView>
    </androidx.constraintlayout.widget.ConstraintLayout>

这是活动代码

HomeActivity.java:

public class HomeActivity extends AppCompatActivity {
    private  String url = "url/to/json.file";
    private RecyclerView mList;
    private LinearLayoutManager linearLayoutManager;
    private List<News> newsList;
    private RecyclerView.Adapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        newsList = new ArrayList<>();
        mList = findViewById(R.id.rv_main_list);
        adapter = new NewsAdapter(newsList);
        mList.setHasFixedSize(true);
        mList.setLayoutManager(new LinearLayoutManager(this));
        mList.setAdapter(adapter);

        getData();
    }

这是我从适配器膨胀并从 JSON 文件设置数据的布局

layout_single_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/linearlayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#673AB7"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

还有适配器类的相关代码,我猜:

@覆盖 公共 NewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); 查看视图 = layoutInflater.inflate(R.layout.layout_single_item, parent, false); ViewHolder viewHolder = new ViewHolder(view); 返回视图持有者; }

@Override
public void onBindViewHolder(@NonNull NewsAdapter.ViewHolder holder, int position) {
    final News currentNews =  newsList.get(position);

    holder.tvTitle.setText(String.valueOf(currentNews.getTitle()));

Glide.with(mContext.getApplicationContext()).load(currentNews.getImage()).into(holder.ivArticleImage); }

    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri newsUri = Uri.parse(currentNews.getNewsLink());
            Intent toWebSiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
            mContext.startActivity(toWebSiteIntent);
        }
    });

ViewHolder 类:

 public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvTitle;
        public ImageView ivArticleImage;
        public LinearLayout linearLayout;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            this.tvTitle = itemView.findViewById(R.id.tv_title);
            this.ivArticleImage = itemView.findViewById(R.id.iv_image);
            linearLayout = itemView.findViewById(R.id.linearlayout);


        }
    }

不知道我做错了什么。感谢您的宝贵时间。

编辑:

getData 函数:

private void getData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                ArrayList<News> newsList = new ArrayList<>();
                for(int i = 0; i < response.length(); i++){
                    try{
                        JSONObject jsonObject = response.getJSONObject(i);
                        News article = new News();
                        article.setTitle(jsonObject.getString("title"));
                        article.setImage(jsonObject.getString("image"));
                        }catch (JSONException e){
                        e.printStackTrace();
                        progressDialog.dismiss();
                    }
                }
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
                progressDialog.dismiss();
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonArrayRequest);

    }

更新 2:

进程:com.agencegg.apps.actualitecd,PID:15002 java.lang.NullPointerException:尝试调用虚拟方法'android.content.Context android.content.Context.getApplicationContext()' 在一个空对象上 参考 在 com.agencegg.apps.actualitecd.adapters.NewsAdapter.onBindViewHolder(NewsAdapter.java:73) 在 com.agencegg.apps.actualitecd.adapters.NewsAdapter.onBindViewHolder(NewsAdapter.java:31) //...

【问题讨论】:

  • 从 api 获取数据后是否更新了适配器?最初列表是空的。
  • 致电adapter.notifyDataSetChanged(); ?
  • 用 newsList 更新适配器。在您的适配器类上创建一个方法。 api调用后调用此方法,然后调用adapter.notifyDataSetChanged()。
  • 我没有使用 API,它是指向 JSON 文件的直接链接
  • 请分享 getData() 方法代码以便更好地理解。解析json文件中的数据后,从您的适配器调用更新方法。

标签: android json data-binding android-recyclerview


【解决方案1】:

像这样在你的适配器上添加一个方法:

public void update(ArrayList<News> newsList){
            this.newsList = newsList;
        }

像这样更新 onResponse() 方法的列表:

@Override
        public void onResponse(JSONArray response) {
            ArrayList<News> newsList = new ArrayList<>();
            for(int i = 0; i < response.length(); i++){
                try{
                    JSONObject jsonObject = response.getJSONObject(i);
                    News article = new News();
                    article.setTitle(jsonObject.getString("title"));
                    article.setImage(jsonObject.getString("image"));
                    newsList.add(news).
                    }catch (JSONException e){
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.update(newsList)
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }

【讨论】:

  • 评论不用于扩展讨论;这个对话是moved to chat
  • 我还有一个要求
猜你喜欢
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2020-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多