排球无法在Android App中加载Json数据

时间:2019-11-24 14:56:20

标签: android json

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

 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 个答案:

答案 0 :(得分:1)

编辑1

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

替换

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

Edit2

像下面一样初始化RecyclerView

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