Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy phần tử Volley vào ArrayList trên Android

Giới thiệu

Ví dụ cơ bản: GET JSON, parse mảng users, thêm từng name vào ArrayList<String> (duyệt ngược từ cuối về đầu).

Code (MainActivity.java)

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private RequestQueue queue;
    private static final String URL = "https://mocky.io/v2/597c41390f0000d002f4dbd1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);
        queue = Volley.newRequestQueue(this);

        StringRequest request = new StringRequest(Request.Method.GET, URL,
            response -> {
                try {
                    JSONObject obj = new JSONObject(response);
                    JSONArray array = obj.getJSONArray("users");
                    List names = new ArrayList<>();

                    // Duyệt ngược (tùy chọn)
                    for (int i = array.length() - 1; i >= 0; i--) {
                        names.add(array.getJSONObject(i).getString("name"));
                    }

                    textView.setText("Danh sách tên:\n" + names.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    textView.setText("Lỗi parse");
                }
            },
            error -> textView.setText("Lỗi mạng")
        );

        queue.add(request);
    }
}

Quyền

<uses-permission android:name="android.permission.INTERNET" />

Cải tiến

  • Duyệt ngược (i--) chỉ cần nếu muốn đảo thứ tự so với JSON gốc.
  • Thường duyệt xuôi (i++) rồi dùng Collections.reverse() nếu cần.
  • Trong app thật: map sang POJO, hiển thị RecyclerView, cache dữ liệu.