При сохранении данных JSON с сервера в представление переработчика отображается только последний элемент JSON

Я пытаюсь получить данные с моего сервера и сохранить их в представлении переработчика. Код правильный и без ошибок. Приложение запускается, но показывает только последний элемент JSON. Я не знаю, что не так в моем коде. Ниже приведен код моей деятельности:

public class Under8ClubSchedule extends AppCompatActivity {

public ProgressBar progressBar;
private static final String URL="http://prasaurus.com/conn_u8_club_schedule.php";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;

private List<Schedule_Items> listItems;

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

progressBar = (ProgressBar)findViewById(R.id.pb);

recyclerView = (RecyclerView)findViewById(R.id.u8_club_schedule);
recyclerView.setHasFixedSize(true);

recyclerView.setLayoutManager(new LinearLayoutManager(this));

listItems = new ArrayList<>();
adapter = new Adapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);

loadRecyclerViewData();

}

private void loadRecyclerViewData(){
progressBar.setVisibility(View.VISIBLE);

StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {

try {
JSONObject jsonObject = new JSONObject(response);
int success = jsonObject.getInt("success");
if(success == 1) {
JSONArray jsonArray = jsonObject.getJSONArray("under8_club_schedule");

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject_current = jsonArray.getJSONObject(i);
Schedule_Items schedule_items = new Schedule_Items(
jsonObject_current.getString("team_one"),
jsonObject_current.getString("team_two"),
jsonObject_current.getString("score"),
jsonObject_current.getString("league_name"),
jsonObject_current.getString("date"),
jsonObject_current.getString("time"),
jsonObject_current.getString("location")
);
listItems.add(schedule_items);
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG);
}
});

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

}

}

Этот код для моего файла класса адаптера:

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

private List<Schedule_Items> listItems;
private Context context;

public Adapter(List<Schedule_Items> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.schedule_orientation,parent,false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Schedule_Items schedule_items = listItems.get(position);

holder.textView_team_name1.setText(schedule_items.getTeam_name1());
holder.textView_team_name2.setText(schedule_items.getTeam_name2());
holder.textView_score.setText(schedule_items.getScore());
holder.textView_league_name.setText(schedule_items.getLeague_name());
holder.textView_date.setText(schedule_items.getDate());
holder.textView_time.setText(schedule_items.getTime());
holder.textView_location.setText(schedule_items.getLocation());
}

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

public class ViewHolder extends RecyclerView.ViewHolder{

public TextView textView_team_name1;
public TextView textView_team_name2;
public TextView textView_score;
public TextView textView_league_name;
public TextView textView_date;
public TextView textView_time;
public TextView textView_location;

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

textView_team_name1 = (TextView)itemView.findViewById(R.id.team_name1);
textView_team_name2 = (TextView)itemView.findViewById(R.id.team_name2);
textView_score = (TextView)itemView.findViewById(R.id.score);
textView_league_name = (TextView)itemView.findViewById(R.id.league_name);
textView_date = (TextView)itemView.findViewById(R.id.date);
textView_time = (TextView)itemView.findViewById(R.id.time);
textView_location = (TextView)itemView.findViewById(R.id.location);

}
}

Я не могу найти, что не так, все выглядит хорошо для меня, но только один элемент виден, когда я запускаю это действие.

0

Решение

Эти строки должны вызываться внутри onCreate () и вызываться после listItems = new ArrayList<>();

adapter = new Adapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);

и создать функцию внутри адаптера, как это

public void setData(Arraylist<Schedule_Items> items){
this.listItems = items;
notifyDataSetChanged();
}

и вызвать эту функцию, как это.

             for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject_current = jsonArray.getJSONObject(i);
Schedule_Items schedule_items = new Schedule_Items(
jsonObject_current.getString("team_one"),
jsonObject_current.getString("team_two"),
jsonObject_current.getString("score"),
jsonObject_current.getString("league_name"),
jsonObject_current.getString("date"),
jsonObject_current.getString("time"),
jsonObject_current.getString("location")
);
listItems.add(schedule_items);
}
}
adapter.setData(listItems);
2

Другие решения

Вы должны позвонить adapter.notifyDataSetChanged(); после recyclerView.setAdapter(adapter);

1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector