Guest User

Untitled

a guest
Jan 17th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.71 KB | None | 0 0
  1. public class MainActivity extends AppCompatActivity {
  2.  
  3. private static final int CODE_GET_REQUEST = 1024;
  4. private static final int CODE_POST_REQUEST = 1025;
  5.  
  6. //Variaveis dos componentes
  7. EditText editTextHeroId, editTextName, editTextRealname;
  8. RatingBar ratingBar;
  9. Spinner spinnerTeam;
  10. ProgressBar progressBarList;
  11. ListView listView;
  12.  
  13. FloatingActionButton fabAddHero;
  14.  
  15. //vamos usar essa lista para exibir herói na lista
  16. List<Hero> heroList;
  17.  
  18. // como o mesmo botão é usado para criar e atualizar
  19. // precisamos rastrear se é uma atualização ou operação de criação
  20. // para isso, temos esse booleano
  21. boolean isUpdating = false;
  22.  
  23. @Override
  24. protected void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.activity_main);
  27.  
  28. //Pegando referencia dos componentes
  29. editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
  30. editTextName = (EditText) findViewById(R.id.editTextName);
  31. editTextRealname = (EditText) findViewById(R.id.editTextRealname);
  32. ratingBar = (RatingBar) findViewById(R.id.ratingBar);
  33. spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);
  34.  
  35. //buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
  36.  
  37. progressBarList = (ProgressBar) findViewById(R.id.progressBarList);
  38. listView = (ListView) findViewById(R.id.listViewHeroes);
  39.  
  40. heroList = new ArrayList<>();
  41.  
  42. fabAddHero = (FloatingActionButton)findViewById(R.id.fabAddHero);
  43. fabAddHero.setOnClickListener(new View.OnClickListener() {
  44. @Override
  45. public void onClick(View view) {
  46. Intent it = new Intent(MainActivity.this, AddHeroActivity.class);
  47. startActivity(it);
  48. }
  49. });
  50. //Método que retorna a lista de herois da base de dados
  51. readHeroes();
  52. }
  53.  
  54. //Recupera os dados dos herois do banco de dados
  55. private void readHeroes() {
  56. PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
  57. request.execute();
  58. }
  59.  
  60. //Para atualizar a lista de herois
  61. private void refreshHeroList(JSONArray heroes) throws JSONException {
  62. //limpa herois anteriores
  63. heroList.clear();
  64.  
  65. //Cria uma nova lista com os herois atualizados do JSON de resposta
  66. for (int i = 0; i < heroes.length(); i++) {
  67. //getting each hero object
  68. JSONObject obj = heroes.getJSONObject(i);
  69.  
  70. //adiciona os herois a lista
  71. heroList.add(new Hero(
  72. obj.getInt("id"),
  73. obj.getString("name"),
  74. obj.getString("realname"),
  75. obj.getInt("rating"),
  76. obj.getString("teamaffiliation")
  77. ));
  78. }
  79.  
  80. //cria um adapter com a lista de herois
  81. HeroAdapter adapter = new HeroAdapter(heroList);
  82. listView.setAdapter(adapter);
  83. }
  84.  
  85. //classe interna para executar solicitação de rede estendendo um AsyncTask
  86. private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
  87.  
  88. //o URL onde precisa enviar a solicitação
  89. String url;
  90.  
  91. //Os parametros
  92. HashMap<String, String> params;
  93.  
  94. //O código do pedido para definir se é um GET ou POST
  95. int requestCode;
  96.  
  97. //Construtor para inicializar os valores
  98. PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
  99. this.url = url;
  100. this.params = params;
  101. this.requestCode = requestCode;
  102. }
  103.  
  104. //Quando a tarefa começou a exibir uma barra de progresso
  105. @Override
  106. protected void onPreExecute() {
  107. super.onPreExecute();
  108. //progressBarList.setVisibility(View.VISIBLE);
  109. }
  110.  
  111. //Este método dará a resposta do pedido
  112. @Override
  113. protected void onPostExecute(String s) {
  114. super.onPostExecute(s);
  115. // progressBarList.setVisibility(GONE);
  116. try {
  117. JSONObject object = new JSONObject(s);
  118. if (!object.getBoolean("error")) {
  119. // Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
  120. //atualizando o herolista após cada operação
  121. //então nós conseguimos uma lista atualizada
  122. refreshHeroList(object.getJSONArray("heroes"));
  123. }
  124. } catch (JSONException e) {
  125. e.printStackTrace();
  126. }
  127. }
  128.  
  129. //A operação da rede será realizada em segundo plano
  130. @Override
  131. protected String doInBackground(Void... voids) {
  132. RequestHandler requestHandler = new RequestHandler();
  133.  
  134. if (requestCode == CODE_POST_REQUEST)
  135. return requestHandler.sendPostRequest(url, params);
  136.  
  137.  
  138. if (requestCode == CODE_GET_REQUEST)
  139. return requestHandler.sendGetRequest(url);
  140.  
  141. return null;
  142. }
  143. }
  144.  
  145. //Classe interna que cria uma adapter para exibir a lista de herois
  146. class HeroAdapter extends ArrayAdapter<Hero> {
  147.  
  148. //our hero list
  149. List<Hero> heroList;
  150.  
  151. //constructor to get the list
  152. public HeroAdapter(List<Hero> heroList) {
  153. super(MainActivity.this, R.layout.layout_hero_list, heroList);
  154. this.heroList = heroList;
  155. }
  156.  
  157. //Metodo que retorna a lista de heroes
  158. @Override
  159. public View getView(int position, View convertView, ViewGroup parent) {
  160. LayoutInflater inflater = getLayoutInflater();
  161. View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
  162.  
  163. //Pegando referencia dos componentes
  164. TextView textViewName = listViewItem.findViewById(R.id.textViewName);
  165. TextView textViewRealname = listViewItem.findViewById(R.id.textViewRealname);
  166.  
  167. //Pegando referencia dos textViews update e delete
  168. TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
  169.  
  170. final Hero hero = heroList.get(position);
  171.  
  172. textViewName.setText(hero.getName());
  173. textViewRealname.setText(hero.getRealname());
  174.  
  175. //Se o textview clicado for o update
  176. textViewUpdate.setOnClickListener(new View.OnClickListener() {
  177. @Override
  178. public void onClick(View view) {
  179.  
  180. Intent intent = new Intent(MainActivity.this, EditHeroActivity.class);
  181. intent.putExtra("hero", hero);
  182. startActivity(intent);
  183. }
  184. });
  185.  
  186. return listViewItem;
  187. }
  188. }
  189. }
Add Comment
Please, Sign In to add comment