2
\$\begingroup\$

I have an Android project that queries the BART train API. I was curious if updating the UI inside the Retrofit onResponse method is correct or if there is a better way. Below is my code. Also, here is the GitHub link if you want to look at a different file. If there are any other issues you see please let me know. I welcome any and all feedback.

ublic class StationListFragment extends Fragment {

private StationList testList;
private RecyclerView recyclerView;
private StationListAdapter adapter;

public StationListFragment() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_station_list, container, false);

// Set up RecyclerView
recyclerView = v.findViewById(R.id.station_list_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));

// Make API call with retrofit
ApiInterface service = RetrofitClient.getClient().create(ApiInterface.class);
Call<StationList> call = service.getStations();
call.enqueue(new Callback<StationList>() {
  @Override
  public void onResponse(Call<StationList> call, Response<StationList> response) {
    // populate recycler view with the list of stations.
    if (response.isSuccessful()) {
      testList = response.body();
      adapter = new StationListAdapter(getContext(), testList.getRoot().getStations().getStation());
      recyclerView.setAdapter(adapter);
      Log.d("TAG: RESPONSE", new GsonBuilder().setPrettyPrinting().create().toJson(response));
    } else {
      int statusCode = response.code();
      Log.d("TAG: STATUSCODE", Integer.toString(statusCode));
    }
  }

  @Override
  public void onFailure(Call<StationList> call, Throwable t) {
    Log.d("TAG: FAILURE", t.getMessage());
  }
});

return v;
}
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.