Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity {
- private static final int CODE_GET_REQUEST = 1024;
- private static final int CODE_POST_REQUEST = 1025;
- //Variaveis dos componentes
- EditText editTextHeroId, editTextName, editTextRealname;
- RatingBar ratingBar;
- Spinner spinnerTeam;
- ProgressBar progressBarList;
- ListView listView;
- FloatingActionButton fabAddHero;
- //vamos usar essa lista para exibir herói na lista
- List<Hero> heroList;
- // como o mesmo botão é usado para criar e atualizar
- // precisamos rastrear se é uma atualização ou operação de criação
- // para isso, temos esse booleano
- boolean isUpdating = false;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //Pegando referencia dos componentes
- editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
- editTextName = (EditText) findViewById(R.id.editTextName);
- editTextRealname = (EditText) findViewById(R.id.editTextRealname);
- ratingBar = (RatingBar) findViewById(R.id.ratingBar);
- spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);
- //buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
- progressBarList = (ProgressBar) findViewById(R.id.progressBarList);
- listView = (ListView) findViewById(R.id.listViewHeroes);
- heroList = new ArrayList<>();
- fabAddHero = (FloatingActionButton)findViewById(R.id.fabAddHero);
- fabAddHero.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent it = new Intent(MainActivity.this, AddHeroActivity.class);
- startActivity(it);
- }
- });
- //Método que retorna a lista de herois da base de dados
- readHeroes();
- }
- //Recupera os dados dos herois do banco de dados
- private void readHeroes() {
- PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
- request.execute();
- }
- //Para atualizar a lista de herois
- private void refreshHeroList(JSONArray heroes) throws JSONException {
- //limpa herois anteriores
- heroList.clear();
- //Cria uma nova lista com os herois atualizados do JSON de resposta
- for (int i = 0; i < heroes.length(); i++) {
- //getting each hero object
- JSONObject obj = heroes.getJSONObject(i);
- //adiciona os herois a lista
- heroList.add(new Hero(
- obj.getInt("id"),
- obj.getString("name"),
- obj.getString("realname"),
- obj.getInt("rating"),
- obj.getString("teamaffiliation")
- ));
- }
- //cria um adapter com a lista de herois
- HeroAdapter adapter = new HeroAdapter(heroList);
- listView.setAdapter(adapter);
- }
- //classe interna para executar solicitação de rede estendendo um AsyncTask
- private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
- //o URL onde precisa enviar a solicitação
- String url;
- //Os parametros
- HashMap<String, String> params;
- //O código do pedido para definir se é um GET ou POST
- int requestCode;
- //Construtor para inicializar os valores
- PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
- this.url = url;
- this.params = params;
- this.requestCode = requestCode;
- }
- //Quando a tarefa começou a exibir uma barra de progresso
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- //progressBarList.setVisibility(View.VISIBLE);
- }
- //Este método dará a resposta do pedido
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- // progressBarList.setVisibility(GONE);
- try {
- JSONObject object = new JSONObject(s);
- if (!object.getBoolean("error")) {
- // Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
- //atualizando o herolista após cada operação
- //então nós conseguimos uma lista atualizada
- refreshHeroList(object.getJSONArray("heroes"));
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- //A operação da rede será realizada em segundo plano
- @Override
- protected String doInBackground(Void... voids) {
- RequestHandler requestHandler = new RequestHandler();
- if (requestCode == CODE_POST_REQUEST)
- return requestHandler.sendPostRequest(url, params);
- if (requestCode == CODE_GET_REQUEST)
- return requestHandler.sendGetRequest(url);
- return null;
- }
- }
- //Classe interna que cria uma adapter para exibir a lista de herois
- class HeroAdapter extends ArrayAdapter<Hero> {
- //our hero list
- List<Hero> heroList;
- //constructor to get the list
- public HeroAdapter(List<Hero> heroList) {
- super(MainActivity.this, R.layout.layout_hero_list, heroList);
- this.heroList = heroList;
- }
- //Metodo que retorna a lista de heroes
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- LayoutInflater inflater = getLayoutInflater();
- View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
- //Pegando referencia dos componentes
- TextView textViewName = listViewItem.findViewById(R.id.textViewName);
- TextView textViewRealname = listViewItem.findViewById(R.id.textViewRealname);
- //Pegando referencia dos textViews update e delete
- TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
- final Hero hero = heroList.get(position);
- textViewName.setText(hero.getName());
- textViewRealname.setText(hero.getRealname());
- //Se o textview clicado for o update
- textViewUpdate.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent intent = new Intent(MainActivity.this, EditHeroActivity.class);
- intent.putExtra("hero", hero);
- startActivity(intent);
- }
- });
- return listViewItem;
- }
- }
- }
Add Comment
Please, Sign In to add comment