Items not displaying in RecyclerView

北城以北 提交于 2021-01-29 12:30:48

问题


That's a weird problem I'm facing right now. From my app, I'm fetch data from JSON file from a link then parse it with Volley. Now I want to display the data on a RecyclerView which doesn't seem to work, I'm pretty dure that my code is good but something doesn't seem to work and I can't find it.

activity_home.xml

This seems to render as I tested wiht background color:

<?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>

Here is the activity code

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

This is the layout I'm inflating from the adapter and set data from JSON file

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>

And the adapter class relevant code, I guess:

@Override public NewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View view = layoutInflater.inflate(R.layout.layout_single_item, parent, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; }

@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 class:

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


        }
    }

Not sure what I'm doing wrong. Thanks for your time.

Edit:

getData function:

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

    }

Update 2:

Process: com.agencegg.apps.actualitecd, PID: 15002 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at com.agencegg.apps.actualitecd.adapters.NewsAdapter.onBindViewHolder(NewsAdapter.java:73) at com.agencegg.apps.actualitecd.adapters.NewsAdapter.onBindViewHolder(NewsAdapter.java:31) //...


回答1:


Add a method on your adapter like this:

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

Update your list on onResponse() method like this way:

@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();
        }
    }


来源:https://stackoverflow.com/questions/55763838/items-not-displaying-in-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!