Volley 无法在 android 应用程序中加载 Json 数据

罗希特

这是我的 Volley String 请求(我为此使用了 Volley 库):

 StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject("response");
                JSONArray jsonArray = jsonObject.getJSONArray("holidays");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    MyModel myModel = new MyModel(jsonObject1.getString("name"), jsonObject1.getString("description"), jsonObject1.getString("iso"));
                    myModelList.add(myModel);
                }
                MyAdapter myAdapter = new MyAdapter(getApplicationContext(), myModelList);
                recyclerView.setAdapter(myAdapter);
            } catch (JSONException e) {

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

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

我正在使用一个简单的回收器视图并想加载“名称”、“描述”

这是 API 响应:

{
  "meta": {
    "code": 200
  },
  "response": {
    "holidays": [
      {
        "name": "New Year's Day",
        "description": "New Year\u2019s Day is celebrated many countries such as in India on the January 1 in the Gregorian calendar.",
        "date": {
          "iso": "2019-01-01",
          "datetime": {
            "year": 2019,
            "month": 1,
            "day": 1
          }
        },
        "type": [
          "National holiday"
        ],
        "locations": "All",
        "states": "All"
      },
      {
        "name": "Guru Govind Singh Jayanti",
        "description": "Guru Gobind Singh Jayanti is the Sikh annual celebration that occurs in countries such as India around December or January in the Gregorian calendar.",
        "date": {
          "iso": "2019-01-13",
          "datetime": {
            "year": 2019,
            "month": 1,
            "day": 13
          }
        },
        "type": [
          "Observance"
        ],
        "locations": "All",
        "states": "All"
      },
      {
        "name": "Lohri",
        "description": null,
        "date": {
          "iso": "2019-01-13",
          "datetime": {
            "year": 2019,
            "month": 1,
            "day": 13
          }
        },
        "type": [
          "National holiday"
        ],
        "locations": "All",
        "states": "All"
      },
      {
        "name": "New Year's Eve",
        "description": "New Year\u2019s Eve is the last day of the year, December 31, in the Gregorian calendar.",
        "date": {
          "iso": "2019-12-31",
          "datetime": {
            "year": 2019,
            "month": 12,
            "day": 31
          }
        },
        "type": [
          "Observance"
        ],
        "locations": "All",
        "states": "All"
      }
    ]
  }
}

这是我的模型类:

public class MyModel {
String name,description;

public MyModel(String name, String description) {
    this.name = name;
    this.description = description;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}
}

这是我的 AdapterClass:

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

Context context;

public MyAdapter(Context context, List<MyModel> myModelList) {
    this.context = context;
    this.myModelList = myModelList;
}

List<MyModel> myModelList;

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.list_layout, parent,false);
    return new ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    MyModel myModel = myModelList.get(position);
    holder.description.setText(myModel.getDescription());
    holder.name.setText(myModel.getName());
 //   holder.iso.setText(myModel.getIso());

}

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

class ViewHolder extends RecyclerView.ViewHolder {
    TextView name, description, iso;

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

        name = itemView.findViewById(R.id.name);
        description = itemView.findViewById(R.id.description);
      //  iso = itemView.findViewById(R.id.iso);
    }
}
}

这是我的 MainActivity.java:

    RecyclerView recyclerView;

    List<MyModel> myModelList;
    // https://calendarific.com/api/v2/holidays?api_key=7b30b25a8d7fe05f34eddfb3d3e9a033828778eb&country=IN&year=2019
    public static final String URL = "https://calendarific.com/api/v2/holidays?api_key=7b30b25a8d7fe05f34eddfb3d3e9a033828778eb&country=IN&year=2019";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerView);
        myModelList = new ArrayList<>();
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("Response : ", response);

                try {
                 JSONObject jsonObject = new JSONObject(response);
////
//                    JSONArray jsonArray = jsonObject.getJSONArray("holidays");
                    JSONObject responseObject = jsonObject.getJSONObject("response");
                    JSONArray jsonArray = responseObject.getJSONArray("holidays");
                    Log.e("sdsd", String.valueOf(jsonArray));


                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        MyModel myModel = new MyModel(jsonObject1.getString("name"), jsonObject1.getString("description"));
                        myModelList.add(myModel);
                    }
                    MyAdapter myAdapter = new MyAdapter(getApplicationContext(), myModelList);
                    recyclerView.setAdapter(myAdapter);
                } catch (JSONException e) {

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

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

做完一切后,recyclerView 还是空的。我怎样才能解决这个问题?

斯瓦扬吉特

编辑1

您将“响应”作为字符串文字传递,如下所示

代替

JSONObject jsonObject = new JSONObject("response");

JSONObject jsonObject = new JSONObject(response);

然后访问假期对象,如下所示

 JSONObject responseObject = jsonObject.getJSONObject("response");
 JSONArray jsonArray = responseObject.getJSONArray("holidays");
 for (int i = 0; i < jsonArray.length(); i++) {
          JSONObject jsonObject1 = jsonArray.getJSONObject(i);
          JSONObject dateJson = jsonObject1.getJSONObject("date");
          String iso = dateJson.getString("iso");
          MyModel myModel = new MyModel(jsonObject1.getString("name"), jsonObject1.getString("description"), jsonObject1.getString("iso"));
          myModelList.add(myModel);
 }

编辑2

初始化RecyclerView如下

recyclerView = findViewById(R.id.recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法在Android中[使用Volley Library]提取JSON数据

Android Volley无法获取数据作为响应

Android Kotlin Volley 如何发送 JSON 数据

无法使用android-volley从JSON数组获取数据到自定义listview

我无法使用JSON和Volley将请求中的数据共享给其他android活动

无法在Android Studio模拟器中加载应用程序

使用AngularJs在Android Cordova应用程序中加载Rest数据

无法在Android应用程序中打印JSON数据的列表视图

Volley Response无法将数据存储到对象Java android

Android Volley将json数据发布到服务器

使用 Android Volley 发布和获取 Json 数据

Android Volley JSON响应

Android Volley:无法解析符号Volley

如何从在线资源在我的Android应用程序中加载数据,我可以在其中轻松添加/更新内容?

SwiftUI - 无法在应用程序中正确显示 JSON 数据

无法从应用程序接收json数据发布

NodeJS - Express 无法读取应用程序/json 数据

Android 应用程序无法将数据写入 Firebase

无法加载json数据

JSON数据存储在哪里?(Android应用程序开发)

JSON将数据解析为android应用程序

JSON Android应用程序,检索数据问题

从android应用程序中的php文件读取JSON数据

Angular JS 应用程序无法从 Web Service 加载数据

Android 登录注册:无法使用 volley 将数据插入数据库

在 Android 应用中使用 Volley 库解析对象数据

无法从android应用中的服务器获取json数据

Android Volley onResponse获取数据

无法在Windows应用程序中加载XML文件