使用 recyclerview 和 volley 错误解析 JSON 数据

如何解决使用 recyclerview 和 volley 错误解析 JSON 数据

我正在尝试按照 thisMysqL 获取 JSON 数据到 Android 应用程序。我收到此错误 E/RecyclerView: No adapter attached; skipping layout。我尝试查找其他帖子的建议,但仍然无法解决问题。以下是我正在处理的代码

import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolBox.StringRequest;
import com.android.volley.toolBox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String HI ="http://xxx/PHPMyAdmin-5.0.4/Appi.PHP" ;   //xxx is ip and the user name
    private List<List_Data> list_data;
    private RecyclerView rv;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv=(RecyclerView)findViewById(R.id.recyclerView);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new linearlayoutmanager(this));
        list_data=new ArrayList<>();
        adapter=new MyAdapter(list_data);

        getMovieData();

    }

    private void getMovieData() {
        StringRequest stringRequest=new StringRequest(Request.Method.GET,HI,new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");
                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        List_Data listData=new List_Data(ob.getString("name"),ob.getString("moive"));
                        list_data.add(listData);
                    }
                    rv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printstacktrace();
                }

            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}

JSON 格式为:

 [{"ID":"1","name":"ab","movie":"cd"},{"ID":"2","name":"ef","movie":"gh"}]

适配器是:

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    private List<List_Data>list_data;

    public MyAdapter(List<List_Data> list_data) {
        this.list_data = list_data;
    }

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

    @Override
    public void onBindViewHolder(ViewHolder holder,int position) {
        List_Data listData=list_data.get(position);
        holder.txtname.setText(listData.getName());
        holder.txtmovie.setText(listData.getMoviename());
    }

    @Override
    public int getItemCount() {

        return list_data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView txtname,txtmovie;
        public ViewHolder(View itemView) {
            super(itemView);
            txtname=(TextView)itemView.findViewById(R.id.txt_name);
            txtmovie=(TextView)itemView.findViewById(R.id.txt_moviename);
        }
    }
}

另外,我像这样设置类:

    public class List_Data {
    private String name;
    private String moviename;

    public List_Data(String name,String moviename) {
        this.name = name;
        this.moviename = moviename;
    }

    public String getName() {
        return name;
    }

    public String getMoviename() {
        return moviename;
    }
}

activity_main.xml 是:

<RelativeLayout
    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=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

还有 lis_data.xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<androidx.cardview.widget.CardView
    android:padding="10dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <LinearLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <LinearLayout
            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <TextView
                android:textColor="#111"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name:"/>

            <TextView
                android:id="@+id/txt_name"
                android:textColor="#111"
                android:layout_marginLeft="10dp"
                style="@style/Base.TextAppearance.AppCompat.Medium"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_marginLeft="10dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
            <TextView
                android:textColor="#111"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="moivename:"/>

            <TextView
                android:id="@+id/txt_moviename"
                android:textColor="#111"
                android:layout_marginLeft="10dp"
                style="@style/Base.TextAppearance.AppCompat.Medium"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>
    </LinearLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

预先感谢您的建议!

解决方法

在您的代码中,当获得新数据时,适配器将始终重新设置。最好设置一次适配器,并在获得新数据时通知数据更改。 这是我的建议。 onCreate 设置回收器视图适配器

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rv=(RecyclerView)findViewById(R.id.recyclerView);
    rv.setHasFixedSize(true);
    rv.setLayoutManager(new LinearLayoutManager(this));
    list_data=new ArrayList<>();
    adapter=new MyAdapter(list_data);
    // set adapter
    rv.setAdapter(adapter);
    getMovieData();

}

在数据更新后的getMovieData()中,调用adapter.notifyDataSetChanged()而不是设置新的适配器

private void getMovieData() {
    StringRequest stringRequest=new StringRequest(Request.Method.GET,HI,new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject=new JSONObject(response);
                JSONArray array=jsonObject.getJSONArray("data");
                for (int i=0; i<array.length(); i++ ){
                    JSONObject ob=array.getJSONObject(i);
                    List_Data listData=new List_Data(ob.getString("name"),ob.getString("moive"));
                    list_data.add(listData);
                }
                adapter.notifyDataSetChanged()
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    },new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue= Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
,

您可以使用以下代码

  public class MainActivity extends AppCompatActivity {
    private static final String HI ="http://xxx/phpMyAdmin-5.0.4/Appi.php" ;   //xxx 
       is ip and the user name
    private List<List_Data> list_data;
    private RecyclerView rv;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv=(RecyclerView)findViewById(R.id.recyclerView);
        rv.setHasFixedSize(true);
        rv.setLayoutManager(new LinearLayoutManager(this));
        list_data=new ArrayList<>();
     
        getMovieData();

    }

    private void getMovieData() {
        StringRequest stringRequest=new StringRequest(Request.Method.GET,new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");
                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        List_Data listData=new List_Data(ob.getString("name"),ob.getString("moive"));
                        list_data.add(listData);
                    }
                       setAdapter(listData)
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

     public void setAdapter(List<List_Data> list_data){

  adapter=new MyAdapter(list_data);
    rv.setAdapter(adapter);
    

   }
   }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?