-2

i have the json data like below

[
{
    "user": "sam",
    "comment": "jjjjjj",


},
{
    "user": "vishnu",
    "comment": "hello",


},
{
    "user": "ijas",
    "comment": "hello  bachanji ",

},
{
    "user": "kiran",
    "comment": "bye",
  }
]

i display all the data in recycle view using adapter, actualy i want to display the first two data that is

{
"user": "sam",
"comment": "jjjjjj",
}
{
"user": "vishnu",
"comment": "hello",
}

i fetch data using the below code

List<Data> data=new ArrayList<>();
for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Data current= new Data();
                    current.user=json_data.getString("user");
                    current.comment= json_data.getString("comment");
                    data.add(current);

how can display the first two data

Sam
  • 45
  • 1
  • 8

3 Answers3

2
List<Data> data=new ArrayList<>();
int length = jArray.length() > 2 ? 2: jArray.length()
for(int i=0;i<length;i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Data current= new Data();
                    current.user=json_data.getString("user");
                    current.comment= json_data.getString("comment");
                    data.add(current);
X3Btel
  • 1,408
  • 1
  • 13
  • 21
1
List<Data> data=new ArrayList<>();
for(int i=0;i<2;i++){
                JSONObject json_data =     jArray.getJSONObject(i);
                Data current= new Data();
                    current.user=json_data.getString("user");
                current.comment=     json_data.getString("comment");
                data.add(current);
}
Rishabh Maurya
  • 1,448
  • 3
  • 22
  • 40
1

Simply you can iterate the list two times and render in UI.

for(int i =0; i< 2; i++){
   Data current = data.get(i);//But we need to check if there is less than 2 entries
   String userName = current.user;
   String comment = current.comment;
   //Now display them
   //Also you can show them in different TextViews
   userNameTextView[i].setText(userName);
   comment[i].setText(comment);
}

That way you can show any number of data.

But usually we use different Adapters to show in list.

Community
  • 1
  • 1
Nabin
  • 11,216
  • 8
  • 63
  • 98