Giới thiệu
Parse JSON thành list đối tượng UserInfo (name, email), sau đó dùng Collections.reverse() để đảo ngược list.
Code chính (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 list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject u = array.getJSONObject(i);
list.add(new UserInfo(u.getString("name"), u.getString("email")));
}
Collections.reverse(list); // Đảo ngược list đối tượng
UserInfo first = list.get(0);
textView.setText("Email: " + first.email + "\nName: " + first.name);
} catch (Exception e) {
e.printStackTrace();
textView.setText("Lỗi");
}
},
error -> textView.setText("Lỗi mạng")
);
queue.add(request);
}
private static class UserInfo {
String name, email;
UserInfo(String name, String email) { this.name = name; this.email = email; }
}
}
Lưu ý
- Class
UserInfokhông cần implementComparablevì chỉ dùng reverse. - Nếu muốn sắp xếp theo email rồi đảo ngược:
Collections.sort(list, Comparator.comparing(u -> u.email)); Collections.reverse(list);