DigimonAPI
This commit is contained in:
78
app/src/main/java/com/example/apidigimon/MainActivity.java
Normal file
78
app/src/main/java/com/example/apidigimon/MainActivity.java
Normal file
@@ -0,0 +1,78 @@
|
||||
package com.example.apidigimon;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.widget.Toast;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.appcompat.widget.SearchView;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import java.util.List;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class MainActivity extends AppCompatActivity {
|
||||
|
||||
private RecyclerView rv;
|
||||
private DigimonAdapter adapter;
|
||||
private SearchView searchView;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_main);
|
||||
|
||||
// Iniciar componentes
|
||||
rv = findViewById(R.id.recyclerViewDigimon);
|
||||
searchView = findViewById(R.id.searchView);
|
||||
rv.setLayoutManager(new LinearLayoutManager(this));
|
||||
|
||||
// Configurar Retrofit
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl("https://digimon-api.vercel.app/api/")
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
|
||||
DigimonService service = retrofit.create(DigimonService.class);
|
||||
|
||||
// Chamar a API
|
||||
service.getDigimons().enqueue(new Callback<List<Digimon>>() {
|
||||
@Override
|
||||
public void onResponse(Call<List<Digimon>> call, Response<List<Digimon>> response) {
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
// Criar o adapter com a lista que veio da internet
|
||||
adapter = new DigimonAdapter(MainActivity.this, response.body());
|
||||
rv.setAdapter(adapter);
|
||||
|
||||
// Configurar o filtro da barra de pesquisa só depois de termos os dados
|
||||
configurarPesquisa();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<List<Digimon>> call, Throwable t) {
|
||||
Toast.makeText(MainActivity.this, "Erro de rede!", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void configurarPesquisa() {
|
||||
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
|
||||
@Override
|
||||
public boolean onQueryTextSubmit(String query) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onQueryTextChange(String newText) {
|
||||
// Filtra a lista enquanto o utilizador escreve
|
||||
if (adapter != null) {
|
||||
adapter.filtrar(newText);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user