Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.86 KB | None | 0 0
  1. package id.co.blogspot.diansano.myheroapp;
  2.  
  3. import android.content.DialogInterface;
  4. import android.os.AsyncTask;
  5. import android.os.Bundle;
  6. import android.text.TextUtils;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.ArrayAdapter;
  11. import android.widget.Button;
  12. import android.widget.EditText;
  13. import android.widget.ListView;
  14. import android.widget.ProgressBar;
  15. import android.widget.RatingBar;
  16. import android.widget.Spinner;
  17. import android.widget.TextView;
  18. import android.widget.Toast;
  19.  
  20. import androidx.annotation.NonNull;
  21. import androidx.annotation.Nullable;
  22. import androidx.appcompat.app.AlertDialog;
  23. import androidx.appcompat.app.AppCompatActivity;
  24.  
  25. import org.json.JSONArray;
  26. import org.json.JSONException;
  27. import org.json.JSONObject;
  28.  
  29. import java.util.ArrayList;
  30. import java.util.HashMap;
  31. import java.util.List;
  32.  
  33. import static android.view.View.GONE;
  34.  
  35. public class MainActivity extends AppCompatActivity {
  36.  
  37. private static final int CODE_GET_REQUEST = 1024;
  38. private static final int CODE_POST_REQUEST = 1025;
  39.  
  40. //defining views
  41. EditText editTextHeroId, editTextName, editTextRealname;
  42. RatingBar ratingBar;
  43. Spinner spinnerTeam;
  44. ProgressBar progressBar;
  45. ListView listView;
  46. Button buttonAddUpdate;
  47.  
  48. //we will use this list to display hero in listview
  49. List<Hero> heroList;
  50.  
  51. //as the same button is used for create and update
  52. //we need to track whether it is an update or create operation
  53. //for this we have this boolean
  54. boolean isUpdating = false;
  55.  
  56. @Override
  57. protected void onCreate(Bundle savedInstanceState) {
  58. super.onCreate(savedInstanceState);
  59. setContentView(R.layout.activity_main);
  60.  
  61. editTextHeroId = findViewById(R.id.editTextHeroId);
  62. editTextName = findViewById(R.id.editTextName);
  63. editTextRealname = findViewById(R.id.editTextRealname);
  64. ratingBar = findViewById(R.id.ratingBar);
  65. spinnerTeam = findViewById(R.id.spinnerTeamAffiliation);
  66.  
  67. buttonAddUpdate = findViewById(R.id.buttonAddUpdate);
  68.  
  69. progressBar = findViewById(R.id.progressBar);
  70. listView = findViewById(R.id.listViewHeroes);
  71.  
  72. heroList = new ArrayList<>();
  73.  
  74. buttonAddUpdate.setOnClickListener(new View.OnClickListener() {
  75. @Override
  76. public void onClick(View view) {
  77. //if it is updating
  78. if (isUpdating) {
  79. //calling the method update hero
  80. //method is commented because it is not yet created
  81. //updateHero();
  82. } else {
  83. //if it is not updating
  84. //that means it is creating
  85. //so calling the method create hero
  86. createHero();
  87. }
  88. }
  89. });
  90.  
  91. //calling the method read heroes to read existing heroes from the database
  92. //method is commented because it is not yet created
  93. readHeroes();
  94. }
  95.  
  96. private void createHero() {
  97. String name = editTextName.getText().toString().trim();
  98. String realname = editTextRealname.getText().toString().trim();
  99.  
  100. int rating = (int) ratingBar.getRating();
  101.  
  102. String team = spinnerTeam.getSelectedItem().toString();
  103.  
  104. //validating the inputs
  105. if (TextUtils.isEmpty(name)) {
  106. editTextName.setError("Please enter name");
  107. editTextName.requestFocus();
  108. return;
  109. }
  110.  
  111. if (TextUtils.isEmpty(realname)) {
  112. editTextRealname.setError("Please enter real name");
  113. editTextRealname.requestFocus();
  114. return;
  115. }
  116.  
  117. //if validation passes
  118. HashMap<String, String> params = new HashMap<>();
  119. params.put("name", name);
  120. params.put("realname", realname);
  121. params.put("rating", String.valueOf(rating));
  122. params.put("teamaffiliation", team);
  123.  
  124. //Calling the create hero API
  125. PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_CREATE_HERO, params,
  126. CODE_POST_REQUEST);
  127. request.execute();
  128. }
  129.  
  130. //inner class to perform network request extending an AsyncTask
  131. private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
  132.  
  133. //the url where we need to send the request
  134. String url;
  135.  
  136. //the parameters
  137. HashMap<String, String> params;
  138.  
  139. //the request code to define whether it is a GET or POST
  140. int requestCode;
  141.  
  142. //constructor to initialize values
  143.  
  144.  
  145. public PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
  146. this.url = url;
  147. this.params = params;
  148. this.requestCode = requestCode;
  149. }
  150.  
  151. //when the task started displaying a progressbar
  152. @Override
  153. protected void onPreExecute() {
  154. super.onPreExecute();
  155. progressBar.setVisibility(GONE);
  156. }
  157.  
  158. //this method will give the response from the request
  159. @Override
  160. protected void onPostExecute(String s) {
  161. super.onPostExecute(s);
  162. progressBar.setVisibility(GONE);
  163.  
  164. try {
  165. JSONObject object = new JSONObject(s);
  166. if (!object.getBoolean("error")) {
  167. Toast.makeText(getApplicationContext(), object.getString("message"),
  168. Toast.LENGTH_SHORT).show();
  169. //refreshing the herolist after every operation
  170. //so we get an updated list
  171. //we will create this method right now it is commented
  172. //because we haven't created it yet
  173. refreshHeroList(object.getJSONArray("heroes"));
  174. }
  175. } catch (JSONException e) {
  176. e.printStackTrace();
  177. }
  178. }
  179.  
  180. //the network operation will be performed in background
  181. @Override
  182. protected String doInBackground(Void... voids) {
  183. RequestHandler requestHandler = new RequestHandler();
  184.  
  185. if (requestCode == CODE_POST_REQUEST)
  186. return requestHandler.sendPostRequest(url, params);
  187.  
  188. if (requestCode == CODE_GET_REQUEST)
  189. return requestHandler.sendGetRequest(url);
  190.  
  191. return null;
  192. }
  193. }
  194.  
  195. class HeroAdapter extends ArrayAdapter<Hero> {
  196. //our hero list
  197. List<Hero> heroList;
  198.  
  199. //contructor to get the list
  200. public HeroAdapter(List<Hero> heroList) {
  201. super(MainActivity.this, R.layout.layout_hero_list, heroList);
  202. this.heroList = heroList;
  203. }
  204.  
  205. //method returning list item
  206.  
  207. @NonNull
  208. @Override
  209. public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
  210. LayoutInflater inflater = getLayoutInflater();
  211. View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
  212.  
  213. //getting the textview for displaying name
  214. TextView textViewName = listViewItem.findViewById(R.id.textViewName);
  215.  
  216. //the update and delete textview
  217. TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
  218. TextView textViewDelete = listViewItem.findViewById(R.id.textViewDelete);
  219.  
  220. final Hero hero = heroList.get(position);
  221.  
  222. textViewName.setText(hero.getName());
  223.  
  224. //attaching click listener to update
  225. textViewUpdate.setOnClickListener(new View.OnClickListener() {
  226. @Override
  227. public void onClick(View view) {
  228. //so when it is updating we will
  229. //make the isUpdating as true
  230. isUpdating = true;
  231.  
  232. //we will set the selected hero to the UI elements
  233. editTextHeroId.setText(String.valueOf(hero.getId()));
  234. editTextName.setText(hero.getName());
  235. editTextRealname.setText(hero.getRealname());
  236. ratingBar.setRating(hero.getRating());
  237. spinnerTeam.setSelection(((ArrayAdapter<String>)spinnerTeam.getAdapter())
  238. .getPosition(hero.getTeamaffiliation()));
  239.  
  240. //we will also make the button text to Update
  241. buttonAddUpdate.setText("Update");
  242. }
  243. });
  244.  
  245. //when the user selected delete
  246. textViewDelete.setOnClickListener(new View.OnClickListener() {
  247. @Override
  248. public void onClick(View view) {
  249.  
  250. //we will display a confirmation dialog before deleting
  251. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
  252.  
  253. builder.setTitle("Delete " + hero.getName())
  254. .setMessage("Are you sure you want to delete it?")
  255. .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
  256. @Override
  257. public void onClick(DialogInterface dialogInterface, int i) {
  258. //if the choice is yes we will delete the hero
  259. //method is commented because it is not yet created
  260. //deleteHero(hero.getId());
  261. }
  262. })
  263. .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
  264. @Override
  265. public void onClick(DialogInterface dialogInterface, int i) {
  266.  
  267. }
  268. })
  269. .setIcon(android.R.drawable.ic_dialog_alert)
  270. .show();
  271. }
  272. });
  273.  
  274. return listViewItem;
  275. }
  276. }
  277.  
  278. private void readHeroes() {
  279. PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null,
  280. CODE_GET_REQUEST);
  281. request.execute();
  282. }
  283.  
  284. private void refreshHeroList(JSONArray heroes) throws JSONException {
  285. //clearing previous heroes
  286. heroList.clear();
  287.  
  288. //traversing through all the items in the json array
  289. //the json we got from the response
  290. for (int i = 0; i < heroes.length(); i++) {
  291. //getting each hero object
  292. JSONObject obj = heroes.getJSONObject(i);
  293.  
  294. //adding the hero to the list
  295. heroList.add(new Hero(obj.getInt("id"),
  296. obj.getString("name"),
  297. obj.getString("realname"),
  298. obj.getInt("rating"),
  299. obj.getString("teamaffiliation")
  300. ));
  301. }
  302.  
  303.  
  304. //creating the adapter and setting it to the listview
  305. HeroAdapter adapter = new HeroAdapter(heroList);
  306. listView.setAdapter(adapter);
  307. }
  308.  
  309. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement