项目不在RecyclerView中显示

时间:2019-04-19 15:02:00

标签: android json data-binding android-recyclerview

这是我现在面临的一个奇怪的问题。 从我的应用程序中,我从链接的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>

与适配器类相关的代码,我想:

@Override     public NewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType){         LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());         视图view = layoutInflater.inflate(R.layout.layout_single_item,parent,false);         ViewHolder viewHolder = new ViewHolder(view);         返回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类:

 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)//...

1 个答案:

答案 0 :(得分: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();
        }
    }