Skip to content

Instantly share code, notes, and snippets.

@TranBaVinhSon
Created March 7, 2018 14:05
Show Gist options
  • Save TranBaVinhSon/bc1abdc11fe193886d8853779d59ca26 to your computer and use it in GitHub Desktop.
Save TranBaVinhSon/bc1abdc11fe193886d8853779d59ca26 to your computer and use it in GitHub Desktop.
package com.example.sontbv.retrofittutorial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.sontbv.retrofittutorial.adapter.MoviesAdapter;
import com.example.sontbv.retrofittutorial.model.Movie;
import com.example.sontbv.retrofittutorial.webservice.ApiInterface;
import com.example.sontbv.retrofittutorial.webservice.ServiceGenerator;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getSimpleName();
private RecyclerView recyclerView;
private List<Movie> movies = new ArrayList<>();
private MoviesAdapter moviesAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(linearLayoutManager);
moviesAdapter = new MoviesAdapter(MainActivity.this, movies);
recyclerView.setAdapter(moviesAdapter);
getMovies();
}
private void getMovies(){
ApiInterface apiInterface = ServiceGenerator.createService(ApiInterface.class);
Call<List<Movie>> call = apiInterface.getMovies();
call.enqueue(new Callback<List<Movie>>() {
@Override
public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
if(response.isSuccessful()) {
for(Movie movie: response.body()){
movies.add(movie);
}
moviesAdapter.notifyDataSetChanged();
}else{
Log.e(TAG, response.message());
}
}
@Override
public void onFailure(Call<List<Movie>> call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment