Created
January 15, 2017 08:17
-
-
Save travisdachi/b8b1c70f4e2c414abbe75e51adce9fe2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
RecyclerView recyclerView; | |
SwipeRefreshLayout swipeRefreshLayout; | |
FilmAdapter filmAdapter; | |
StarWarsApi starWarsApi; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
recyclerView = (RecyclerView) findViewById(R.id.rvFilms); | |
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl); | |
setTitle("All Star Wars Films"); | |
filmAdapter = new FilmAdapter(null, new FilmAdapter.OnFilmClickListener() { | |
@Override | |
public void onFilmClick(Film film) { | |
FilmActivity.start(MainActivity.this, film.episodeId); | |
} | |
}); | |
recyclerView.setLayoutManager(new LinearLayoutManager(this)); | |
recyclerView.setAdapter(filmAdapter); | |
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { | |
@Override | |
public void onRefresh() { | |
loadFilms(); | |
} | |
}); | |
Gson gson = new GsonBuilder() | |
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) | |
.create(); | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl("http://swapi.co/api/") | |
.addConverterFactory(GsonConverterFactory.create(gson)) | |
.build(); | |
starWarsApi = retrofit.create(StarWarsApi.class); | |
loadFilms(); | |
} | |
private void loadFilms() { | |
swipeRefreshLayout.setRefreshing(true); | |
starWarsApi.getAllFilms().enqueue(new Callback<FilmResponse>() { | |
@Override | |
public void onResponse(Call<FilmResponse> call, Response<FilmResponse> response) { | |
filmAdapter.setFilms(response.body().results); | |
swipeRefreshLayout.setRefreshing(false); | |
} | |
@Override | |
public void onFailure(Call<FilmResponse> call, Throwable t) { | |
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show(); | |
swipeRefreshLayout.setRefreshing(false); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment