Android MySQL Tutorial To Perform Basic CRUD Operation2
Android MySQL Tutorial To Perform Basic CRUD Operation2
About
Contact Us
Advertise
Privacy Policy
Hello friends, Here is another Android MySQL Tutorial, in this post we will learn the basic CRUD operation in
MySQL database from Android Application. So without wasting time lets start our Android MySQL Tutorial.
Contents
1 What is CRUD?
2 Why PHP and MySQL and Why Not SQLite?
2.1 Do we have only PHP and MySQL for this?
3 Building Web APIs
3.1 Creating Database
3.2 Creating PHP Project
3.2.1 Project Structure
3.2.2 Defining Constants
3.2.3 Connecting to Database
3.2.4 Performing Database Operations
3.2.5 Handling API Calls
3.2.6 Testing the API Calls
3.2.6.1 Create Operation
3.2.6.2 Read Operation
3.2.6.3 Update Operation
3.2.6.4 Delete Operation
3.2.7 Finalizing API Calls
4 Android MySQL Tutorial
4.1 Creating a new Project
4.2 Creating Helper Classes
4.2.1 Class To Store API URLs
4.2.2 Hero Model Class
4.2.3 Request Handler
4.3 Defining Internet Permission in AndroidManifest
4.4 Designing User Interface
4.5 Class to Perform Network Request
4.6 Create Operation
4.7 Read Operation
4.7.1 List Layout
4.7.2 Custom Adapter Class
4.7.3 Retrieving Heroes from the Database
4.8 Update Operation
4.9 Delete Operation
4.10 The complete code for MainActivity
5 Android MySQL Tutorial – Source Code Download
5.1 Sharing is Caring:
5.2 Related
What is CRUD?
I guess many of you already know that what is CRUD. But if anyone don’t know, CRUD is an Acronym for the
Basic Database Operations. In any database we do the following basic operations.
So basically in any database we perform the above mentioned operations. In this tutorial I am going to use
MySQL and PHP.
Obviously NO? You can use any server side scripting language or database application. I am using here PHP
and MySQL because it is easily available and I already know it. 😛 (LOL) But if you are an expert in Python or
JAVA or NodeJS or basically any other technology then you can go with it. It will change only the server side
coding. Android part will always be the same.
So our android device will send a request to our API, then our API will perform the requested task and it will
give us the response related to the task. You can see the below diagram for more clarification.
I guess you got a basic idea about the task that we are going to do in this tutorial.
Creating Database
It is obvious that we need a database first 😛 . So here I am using XAMPP (You can go with wamp or lamp as
well). So first create the following database.
So open localhost/phpmyadmin and run the following query to create the above table.
-- created by Belal
Khan
So inside htdocs (c:/xampp/htdocs) create a new folder (You can also use an IDE like PHP Storm to
create project but remember create the project inside c:/xampp/htdocs only).
I have given the name HeroApi to my project. You can give any name. But I would say give the same
name or else you may lead up to some errors following the post if you are a newbie.
Inside the project create two more folders named includes and Api. You can see the below screenshot for
the directory structure that I am using. (I am using Sublime Text for coding server part).
You see we have four php files (3 inside includes and 1 inside v1). So you create these files as well.
Project Structure
Defining Constants
First come inside the file Constants.php and write the following code.
Constants.php
PHP
<?php
1 <?php
2
3 /*
4 * Created by Belal Khan
5 * website: www.simplifiedcoding.net
6 */
7 define('DB_HOST', 'localhost');
8 define('DB_USER', 'root');
9 define('DB_PASS', '');
10 define('DB_NAME', 'android');
11
Connecting to Database
Now inside DbConnect.php write the following code. I have explained the code using comments.
DbConnect.php
PHP
<?php
1 <?php
2 /*
3 * Created by Belal Khan
4 * website: www.simplifiedcoding.net
5 */
6 //Class DbConnect
7 class DbConnect
8 {
9 //Variable to store database link
10 private $con;
11 //Class constructor
12 function __construct()
13 {
14 }
15 //This method will connect to the database
16 function connect()
17 {
18 //Including the constants.php file to get the database constants
19 include_once dirname(__FILE__) . '/Constants.php';
20 //connecting to mysql database
21 $this->con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
22 //Checking if any error occured while connecting
23 if (mysqli_connect_errno()) {
24 echo "Failed to connect to MySQL: " . mysqli_connect_error();
25 }
26 //finally returning the connection link
27 return $this->con;
28 }
29 }
30
31
32
33
34
35
36
37
38
DbOperation.php
PHP
<?php
1 <?php
2 class DbOperation
3 {
4 //Database connection link
5 private $con;
6 //Class constructor
7 function __construct()
8 {
9 //Getting the DbConnect.php file
10 require_once dirname(__FILE__) . '/DbConnect.php';
11 //Creating a DbConnect object to connect to the database
12 $db = new DbConnect();
13 //Initializing our connection link of this class
14 //by calling the method connect of DbConnect class
15 $this->con = $db->connect();
16 }
17 /*
18 * The create operation
19 * When this method is called a new record is created in the database
20 */
21 function createHero($name, $realname, $rating, $teamaffiliation){
22 $stmt = $this->con->prepare("INSERT INTO heroes (name, realname, rating, teamaffiliation) VALUES (?, ?, ?, ?)");
23 $stmt->bind_param("ssis", $name, $realname, $rating, $teamaffiliation);
24 if($stmt->execute())
25 return true;
26 return false;
27 }
28
29 /*
30 * The read operation
31 * When this method is called it is returning all the existing record of the database
32 */
33 function getHeroes(){
34 $stmt = $this->con->prepare("SELECT id, name, realname, rating, teamaffiliation FROM heroes");
35 $stmt->execute();
36 $stmt->bind_result($id, $name, $realname, $rating, $teamaffiliation);
37 $heroes = array();
38 while($stmt->fetch()){
39 $hero = array();
40 $hero['id'] = $id;
41 $hero['name'] = $name;
42 $hero['realname'] = $realname;
43 $hero['rating'] = $rating;
44 $hero['teamaffiliation'] = $teamaffiliation;
45 array_push($heroes, $hero);
46 }
47 return $heroes;
48 }
49 /*
50 * The update operation
51 * When this method is called the record with the given id is updated with the new given values
52 */
53 function updateHero($id, $name, $realname, $rating, $teamaffiliation){
54 $stmt = $this->con->prepare("UPDATE heroes SET name = ?, realname = ?, rating = ?, teamaffiliation = ? WHERE id = ?");
55 $stmt->bind_param("ssisi", $name, $realname, $rating, $teamaffiliation, $id);
56 if($stmt->execute())
57 return true;
58 return false;
59 }
60 /*
61 * The delete operation
62 * When this method is called record is deleted for the given id
63 */
64 function deleteHero($id){
65 $stmt = $this->con->prepare("DELETE FROM heroes WHERE id = ? ");
66 $stmt->bind_param("i", $id);
67 if($stmt->execute())
68 return true;
69 return false;
70 }
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84
Now here come the main part, which is handling the API calls. So come inside the Api.php which is
inside the v1 folder.
Api.php
PHP
<?php
1 <?php
2
3 //getting the dboperation class
4 require_once '../includes/DbOperation.php';
5
6 //function validating all the paramters are available
7 //we will pass the required parameters to this function
8 function isTheseParametersAvailable($params){
9 //assuming all parameters are available
10 $available = true;
11 $missingparams = "";
12 foreach($params as $param){
13 if(!isset($_POST[$param]) || strlen($_POST[$param])<=0){
14 $available = false;
15 $missingparams = $missingparams . ", " . $param;
16 }
17 }
18 //if parameters are missing
19 if(!$available){
20 $response = array();
21 $response['error'] = true;
22 $response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
23 //displaying error
24 echo json_encode($response);
25 //stopping further execution
26 die();
27 }
28 }
29 //an array to display response
30 $response = array();
31 //if it is an api call
32 //that means a get parameter named api call is set in the URL
33 //and with this parameter we are concluding that it is an api call
34 if(isset($_GET['apicall'])){
35 switch($_GET['apicall']){
36 //the CREATE operation
37 //if the api call value is 'createhero'
38 //we will create a record in the database
39 case 'createhero':
40 //first check the parameters required for this request are available or not
41 isTheseParametersAvailable(array('name','realname','rating','teamaffiliation'));
42 //creating a new dboperation object
43 $db = new DbOperation();
44 //creating a new record in the database
45 $result = $db->createHero(
46 $_POST['name'],
47 $_POST['realname'],
48 $_POST['rating'],
49 $_POST['teamaffiliation']
50 );
51
52 //if the record is created adding success to response
53 if($result){
54 //record is created means there is no error
55 $response['error'] = false;
56
57 //in message we have a success message
58 $response['message'] = 'Hero addedd successfully';
59
60 //and we are getting all the heroes from the database in the response
61 $response['heroes'] = $db->getHeroes();
62 }else{
63
64 //if record is not added that means there is an error
65 $response['error'] = true;
66
67 //and we have the error message
68 $response['message'] = 'Some error occurred please try again';
69 }
70 break;
71 //the READ operation
72 //if the call is getheroes
73 case 'getheroes':
74 $db = new DbOperation();
75 $response['error'] = false;
76 $response['message'] = 'Request successfully completed';
77 $response['heroes'] = $db->getHeroes();
78 break;
79 //the UPDATE operation
80 case 'updatehero':
81 isTheseParametersAvailable(array('id','name','realname','rating','teamaffiliation'));
82 $db = new DbOperation();
83 $result = $db->updateHero(
84 $_POST['id'],
85 $_POST['name'],
86 $_POST['realname'],
87 $_POST['rating'],
88 $_POST['teamaffiliation']
89 );
90 if($result){
91 $response['error'] = false;
92 $response['message'] = 'Hero updated successfully';
93 $response['heroes'] = $db->getHeroes();
94 }else{
95 $response['error'] = true;
96 $response['message'] = 'Some error occurred please try again';
97 }
98 break;
99 //the delete operation
100 case 'deletehero':
101
102 //for the delete operation we are getting a GET parameter from the url having the id of the record to be deleted
103 if(isset($_GET['id'])){
104 $db = new DbOperation();
105 if($db->deleteHero($_GET['id'])){
106 $response['error'] = false;
107 $response['message'] = 'Hero deleted successfully';
108 $response['heroes'] = $db->getHeroes();
109 }else{
110 $response['error'] = true;
111 $response['message'] = 'Some error occurred please try again';
112 }
113 }else{
114 $response['error'] = true;
115 $response['message'] = 'Nothing to delete, provide an id please';
116 }
117 break;
118 }
119 }else{
120 //if it is not api call
121 //pushing appropriate values to response array
122 $response['error'] = true;
123 $response['message'] = 'Invalid API Call';
124 }
125 //displaying the response in json structure
126 echo json_encode($response);
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
For testing the API Calls here I am using POSTMAN. It is a REST API Client for Google Chrome.
Create Operation
Read Operation
Update Operation
Delete Operation
You see all the operations are working absolutely fine. Now we can move ahead in creating our Android Project.
But before moving to android side below you can see our API URLs.
The below table displays our API URLs with the Parameter and Method. Remember using localhost in
android side will not work. You need to find your IP. I have my IP in the below table, but in your
case you need to find yours. So if you are using a windows you can use ipconfig command to find IP
and for MAC or Linux use the ifconfig command. For more details you can visit this tutorial.
Create a new Android Studio Project. Here I have created a project named MyHeroApp.
Once your project is loaded inside the package we will create all the helper classes that is required for thie
project.
First create a class named Api.java and write the following code.
Api.java
Java
package
net.simplifiedlearn
1 package net.simplifiedlearning.myheroapp;
2
3 /**
4 * Created by Belal on 9/9/2017.
5 */
6
7 public class Api {
8
9 private static final String ROOT_URL = "http://192.168.101.1/HeroApi/v1/Api.php?apicall=";
10
11 public static final String URL_CREATE_HERO = ROOT_URL + "createhero";
12 public static final String URL_READ_HEROES = ROOT_URL + "getheroes";
13 public static final String URL_UPDATE_HERO = ROOT_URL + "updatehero";
14 public static final String URL_DELETE_HERO = ROOT_URL + "deletehero&id=";
15
16 }
We also need a model class for our Hero. So create a class named Hero.java and write the following code.
It will have only properties, constructor and getters.
Hero.java
Java
package
net.simplifiedlearn
1 package net.simplifiedlearning.myheroapp;
2
3 import java.io.Serializable;
4
5 /**
6 * Created by Belal on 9/9/2017.
7 */
8
9 class Hero {
10 private int id;
11 private String name, realname;
12 private int rating;
13 private String teamaffiliation;
14
15 public Hero(int id, String name, String realname, int rating, String teamaffiliation) {
16 this.id = id;
17 this.name = name;
18 this.realname = realname;
19 this.rating = rating;
20 this.teamaffiliation = teamaffiliation;
21 }
22
23 public int getId() {
24 return id;
25 }
26
27 public String getName() {
28 return name;
29 }
30
31 public String getRealname() {
32 return realname;
33 }
34
35 public int getRating() {
36 return rating;
37 }
38
39 public String getTeamaffiliation() {
40 return teamaffiliation;
41 }
42 }
Request Handler
We need to send GET and POST request to our API URLs, and for this I am creating a new class that will
perform these tasks. So create a new class named RequestHandler.java and write the following code.
RequestHandler.java
Java
package
net.simplifiedlearn
1 package net.simplifiedlearning.myheroapp;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.OutputStreamWriter;
8 import java.io.UnsupportedEncodingException;
9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLEncoder;
12 import java.util.HashMap;
13 import java.util.Map;
14
15 import javax.net.ssl.HttpsURLConnection;
16
17 /**
18 * Created by Belal on 9/9/2017.
19 */
20 public class RequestHandler {
21
22 //Method to send httpPostRequest
23 //This method is taking two arguments
24 //First argument is the URL of the script to which we will send the request
25 //Other is an HashMap with name value pairs containing the data to be send with the request
26 public String sendPostRequest(String requestURL,
27 HashMap<String, String> postDataParams) {
28 //Creating a URL
29 URL url;
30
31 //StringBuilder object to store the message retrieved from the server
32 StringBuilder sb = new StringBuilder();
33 try {
34 //Initializing Url
35 url = new URL(requestURL);
36
37 //Creating an httmlurl connection
38 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
39
40 //Configuring connection properties
41 conn.setReadTimeout(15000);
42 conn.setConnectTimeout(15000);
43 conn.setRequestMethod("POST");
44 conn.setDoInput(true);
45 conn.setDoOutput(true);
46
47 //Creating an output stream
48 OutputStream os = conn.getOutputStream();
49
50 //Writing parameters to the request
51 //We are using a method getPostDataString which is defined below
52 BufferedWriter writer = new BufferedWriter(
53 new OutputStreamWriter(os, "UTF-8"));
54 writer.write(getPostDataString(postDataParams));
55
56 writer.flush();
57 writer.close();
58 os.close();
59 int responseCode = conn.getResponseCode();
60
61 if (responseCode == HttpsURLConnection.HTTP_OK) {
62
63 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
64 sb = new StringBuilder();
65 String response;
66 //Reading server response
67 while ((response = br.readLine()) != null) {
68 sb.append(response);
69 }
70 }
71
72 } catch (Exception e) {
73 e.printStackTrace();
74 }
75 return sb.toString();
76 }
77
78 public String sendGetRequest(String requestURL) {
79 StringBuilder sb = new StringBuilder();
80 try {
81 URL url = new URL(requestURL);
82 HttpURLConnection con = (HttpURLConnection) url.openConnection();
83 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
84
85 String s;
86 while ((s = bufferedReader.readLine()) != null) {
87 sb.append(s + "\n");
88 }
89 } catch (Exception e) {
90 }
91 return sb.toString();
92 }
93
94
95 private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
96 StringBuilder result = new StringBuilder();
97 boolean first = true;
98 for (Map.Entry<String, String> entry : params.entrySet()) {
99 if (first)
100 first = false;
101 else
102 result.append("&");
103
104 result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
105 result.append("=");
106 result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
107 }
108
109 return result.toString();
110 }
111 }
AndroidManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
1 <?xml version="1.0" encoding="utf-8"?>
2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3 package="net.simplifiedlearning.myheroapp">
4
5 <!-- this is the internet permission -->
6 <uses-permission android:name="android.permission.INTERNET" />
7
8 <application
9 android:allowBackup="true"
10 android:icon="@mipmap/ic_launcher"
11 android:label="@string/app_name"
12 android:roundIcon="@mipmap/ic_launcher_round"
13 android:supportsRtl="true"
14 android:theme="@style/AppTheme">
15 <activity android:name=".MainActivity">
16 <intent-filter>
17 <action android:name="android.intent.action.MAIN" />
18
19 <category android:name="android.intent.category.LAUNCHER" />
20 </intent-filter>
21 </activity>
22 </application>
23
24 </manifest>
So we need to design the above mentioned things. I have already designed the activity_main.xml so you
can directly use the below code.
activity_main.xml
<?xml version="1.0"
encoding="utf-8"?>
For the spinner I have used static entries using xml array. So you also need to create this array. For this go
inside values -> strings.xml
strings.xml
<resources>
<string
1 <resources>
2 <string name="app_name">Android MySQL CRUD</string>
3
4 <!-- defining the array for our spinner -->
5 <array name="teams">
6 <item>Avengers</item>
7 <item>Justice League</item>
8 <item>X-Men</item>
9 <item>Fantastic Four</item>
10 </array>
11 </resources>
Thats it for the User Interface part.
Now lets perform the CRUD operations in our MySQL database.
Java
//inner class
to perform network
Create Operation
Now lets save a new hero to our database. First we will define all the views. And we will attach a
clicklistener to the button and inside the click event we will call the method to create a new record in the
database.
Java
public class
MainActivity
Java
private void
createHero() {
Its working fine, you can check the database as well. Now lets move to the read operation.
Read Operation
We will display all the heroes from the database in a ListView, the ListView also have the Update and
Delete Button.
So for this first we will create a custom Layout for our ListView.
List Layout
layout_hero_list.xml
<?xml version="1.0"
encoding="utf-8"?>
Create one more inner class inside MainActivity class. We will name it HeroAdapter.
HeroAdapter
Java
class HeroAdapter
t d
readHeroes()
Java
private void
readHeroes() {
Now one more method we need to refresh the Hero List. So create a method named refreshHeroList().
refreshHeroList()
Java
private void
refreshHeroList(JSO
You can see it is also working fine. Now lets do the UPDATE operation.
Update Operation
For updating we will create a new method named updateHero().
updateHero()
Java
private void
updateHero() {
1 private void updateHero() {
2 String id = editTextHeroId.getText().toString();
3 String name = editTextName.getText().toString().trim();
4 String realname = editTextRealname.getText().toString().trim();
5
6 int rating = (int) ratingBar.getRating();
7
8 String team = spinnerTeam.getSelectedItem().toString();
9
10
11 if (TextUtils.isEmpty(name)) {
12 editTextName.setError("Please enter name");
13 editTextName.requestFocus();
14 return;
15 }
16
17 if (TextUtils.isEmpty(realname)) {
18 editTextRealname.setError("Please enter real name");
19 editTextRealname.requestFocus();
20 return;
21 }
22
23 HashMap<String, String> params = new HashMap<>();
24 params.put("id", id);
25 params.put("name", name);
26 params.put("realname", realname);
27 params.put("rating", String.valueOf(rating));
28 params.put("teamaffiliation", team);
29
30
31 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_UPDATE_HERO, params,
32 CODE_POST_REQUEST);
33 request.execute();
34
35 buttonAddUpdate.setText("Add");
36
37 editTextName.setText("");
38 editTextRealname.setText("");
39 ratingBar.setRating(0);
40 spinnerTeam.setSelection(0);
41
42 isUpdating = false;
}
Now just uncomment the method updateHero() inside the click listener of buttonAddUpdate.
And now we can try updating a record.
So the update is also working absolutely fine. Now lets move to the last operation which is delete.
Delete Operation
For delete also we need a new method. So create a method named deleteHero().
deleteHero()
Java
private void
deleteHero(int id)
So it is working fine as well. And we have done with all the basic CRUD operations.
If you had some confusions following the above steps here is the complete code for MainActivity.java.
MainActivity.java
Java
package
net.simplifiedlearn
1 package net.simplifiedlearning.myheroapp;
2
3 import android.content.DialogInterface;
4 import android.os.AsyncTask;
5 import android.os.Bundle;
6 import android.support.v7.app.AlertDialog;
7 import android.support.v7.app.AppCompatActivity;
8 import android.text.TextUtils;
9 import android.view.LayoutInflater;
10 import android.view.View;
11 import android.view.ViewGroup;
12 import android.widget.ArrayAdapter;
13 import android.widget.Button;
14 import android.widget.EditText;
15 import android.widget.ListView;
16 import android.widget.ProgressBar;
17 import android.widget.RatingBar;
18 import android.widget.Spinner;
19 import android.widget.TextView;
20 import android.widget.Toast;
21
22 import org.json.JSONArray;
23 import org.json.JSONException;
24 import org.json.JSONObject;
25
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29
30 import static android.view.View.GONE;
31
32 public class MainActivity extends AppCompatActivity {
33
34 private static final int CODE_GET_REQUEST = 1024;
35 private static final int CODE_POST_REQUEST = 1025;
36
37 EditText editTextHeroId, editTextName, editTextRealname;
38 RatingBar ratingBar;
39 Spinner spinnerTeam;
40 ProgressBar progressBar;
41 ListView listView;
42 Button buttonAddUpdate;
43
44 List<Hero> heroList;
45
46 boolean isUpdating = false;
47
48 @Override
49 protected void onCreate(Bundle savedInstanceState) {
50 super.onCreate(savedInstanceState);
51 setContentView(R.layout.activity_main);
52
53 editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
54 editTextName = (EditText) findViewById(R.id.editTextName);
55 editTextRealname = (EditText) findViewById(R.id.editTextRealname);
56 ratingBar = (RatingBar) findViewById(R.id.ratingBar);
57 spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);
58
59 buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
60
61 progressBar = (ProgressBar) findViewById(R.id.progressBar);
62 listView = (ListView) findViewById(R.id.listViewHeroes);
63
64 heroList = new ArrayList<>();
65
66
67 buttonAddUpdate.setOnClickListener(new View.OnClickListener() {
68 @Override
69 public void onClick(View view) {
70 if (isUpdating) {
71 updateHero();
72 } else {
73 createHero();
74 }
75 }
76 });
77 readHeroes();
78 }
79
80
81 private void createHero() {
82 String name = editTextName.getText().toString().trim();
83 String realname = editTextRealname.getText().toString().trim();
84
85 int rating = (int) ratingBar.getRating();
86
87 String team = spinnerTeam.getSelectedItem().toString();
88
89 if (TextUtils.isEmpty(name)) {
90 editTextName.setError("Please enter name");
91 editTextName.requestFocus();
92 return;
93 }
94
95 if (TextUtils.isEmpty(realname)) {
96 editTextRealname.setError("Please enter real name");
97 editTextRealname.requestFocus();
98 return;
99 }
100
101 HashMap<String, String> params = new HashMap<>();
102 params.put("name", name);
103 params.put("realname", realname);
104 params.put("rating", String.valueOf(rating));
105 params.put("teamaffiliation", team);
106
107 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_CREATE_HERO, params,
108 CODE_POST_REQUEST);
109 request.execute();
110 }
111
112 private void readHeroes() {
113 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
114 request.execute();
115 }
116
117 private void updateHero() {
118 String id = editTextHeroId.getText().toString();
119 String name = editTextName.getText().toString().trim();
120 String realname = editTextRealname.getText().toString().trim();
121
122 int rating = (int) ratingBar.getRating();
123
124 String team = spinnerTeam.getSelectedItem().toString();
125
126
127 if (TextUtils.isEmpty(name)) {
128 editTextName.setError("Please enter name");
129 editTextName.requestFocus();
130 return;
131 }
132
133 if (TextUtils.isEmpty(realname)) {
134 editTextRealname.setError("Please enter real name");
135 editTextRealname.requestFocus();
136 return;
137 }
138
139 HashMap<String, String> params = new HashMap<>();
140 params.put("id", id);
141 params.put("name", name);
142 params.put("realname", realname);
143 params.put("rating", String.valueOf(rating));
144 params.put("teamaffiliation", team);
145
146
147 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_UPDATE_HERO, params,
148 CODE_POST_REQUEST);
149 request.execute();
150
151 buttonAddUpdate.setText("Add");
152
153 editTextName.setText("");
154 editTextRealname.setText("");
155 ratingBar.setRating(0);
156 spinnerTeam.setSelection(0);
157
158 isUpdating = false;
159 }
160
161 private void deleteHero(int id) {
162 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_DELETE_HERO + id, null,
163 CODE_GET_REQUEST);
164 request.execute();
165 }
166
167 private void refreshHeroList(JSONArray heroes) throws JSONException {
168 heroList.clear();
169
170 for (int i = 0; i < heroes.length(); i++) {
171 JSONObject obj = heroes.getJSONObject(i);
172
173 heroList.add(new Hero(
174 obj.getInt("id"),
175 obj.getString("name"),
176 obj.getString("realname"),
177 obj.getInt("rating"),
178 obj.getString("teamaffiliation")
179 ));
180 }
181
182 HeroAdapter adapter = new HeroAdapter(heroList);
183 listView.setAdapter(adapter);
184 }
185
186 private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
187 String url;
188 HashMap<String, String> params;
189 int requestCode;
190
191 PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
192 this.url = url;
193 this.params = params;
194 this.requestCode = requestCode;
195 }
196
197 @Override
198 protected void onPreExecute() {
199 super.onPreExecute();
200 progressBar.setVisibility(View.VISIBLE);
201 }
202
203 @Override
204 protected void onPostExecute(String s) {
205 super.onPostExecute(s);
206 progressBar.setVisibility(GONE);
207 try {
208 JSONObject object = new JSONObject(s);
209 if (!object.getBoolean("error")) {
210 Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
211 refreshHeroList(object.getJSONArray("heroes"));
212 }
213 } catch (JSONException e) {
214 e.printStackTrace();
215 }
216 }
217
218 @Override
219 protected String doInBackground(Void... voids) {
220 RequestHandler requestHandler = new RequestHandler();
221
222 if (requestCode == CODE_POST_REQUEST)
223 return requestHandler.sendPostRequest(url, params);
224
225
226 if (requestCode == CODE_GET_REQUEST)
227 return requestHandler.sendGetRequest(url);
228
229 return null;
230 }
231 }
232
233 class HeroAdapter extends ArrayAdapter<Hero> {
234 List<Hero> heroList;
235
236 public HeroAdapter(List<Hero> heroList) {
237 super(MainActivity.this, R.layout.layout_hero_list, heroList);
238 this.heroList = heroList;
239 }
240
241
242 @Override
243 public View getView(int position, View convertView, ViewGroup parent) {
244 LayoutInflater inflater = getLayoutInflater();
245 View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
246
247 TextView textViewName = listViewItem.findViewById(R.id.textViewName);
248
249 TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
250 TextView textViewDelete = listViewItem.findViewById(R.id.textViewDelete);
251
252 final Hero hero = heroList.get(position);
253
254 textViewName.setText(hero.getName());
255
256 textViewUpdate.setOnClickListener(new View.OnClickListener() {
257 @Override
258 public void onClick(View view) {
259 isUpdating = true;
260 editTextHeroId.setText(String.valueOf(hero.getId()));
261 editTextName.setText(hero.getName());
262 editTextRealname.setText(hero.getRealname());
263 ratingBar.setRating(hero.getRating());
264 spinnerTeam.setSelection(((ArrayAdapter<String>) spinnerTeam.getAdapter()).getPosition(hero.getTeamaffiliation()));
265 buttonAddUpdate.setText("Update");
266 }
267 });
268
269 textViewDelete.setOnClickListener(new View.OnClickListener() {
270 @Override
271 public void onClick(View view) {
272
273 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
274
275 builder.setTitle("Delete " + hero.getName())
276 .setMessage("Are you sure you want to delete it?")
277 .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
278 public void onClick(DialogInterface dialog, int which) {
279 deleteHero(hero.getId());
280 }
281 })
282 .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
283 public void onClick(DialogInterface dialog, int which) {
284
285 }
286 })
287 .setIcon(android.R.drawable.ic_dialog_alert)
288 .show();
289
290 }
291 });
292
293 return listViewItem;
}
}
}
So after following every step correctly your application will behave as shown below.
Sharing is Caring:
Tweet
More
Related
Email
SUBSCRIBE!
I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding,
app development, android etc.
Comments
This is great ! Thanks author, i really like your post so much and it is up to date… Thumbs UP !
Reply
2. PRATHAP says
Just blowed away bro..!! just trying for almost two days…bt you made it so simple…10 minutes job…bt it
took more than a days count bt failed even…thankx bro…cheers (y)
Reply
3. Kowa says
Reply
4. Kevien says
Reply
6. laxmi says
Hi Mr.Belal ,this is very much helpful ,thank you so much for this awesome tutorial.
Reply
7. reza says
Reply
8. Amit says
Reply
Reply
Reply
Amazing !!! great job… Never failed to surprise me for running program without error. Keep it up . Best
Tut…
Reply
Reply
Reply
Hi Belal,
Thanks for the tutorial.
the tutorial very easy to understands.Thanks man
Reply
Reply
Reply
Hello VikasYadav, what error its showing, can you share details ?
Reply
I have tried many times, but always the error in the layout / activity_main.xml file in the block below:
ERROR RETURN:
Error: (52, 30) No resource found that matches the given name (at ‘entries’ with value ‘@ array / teams’).
Can anyone help?
thanks
Reply
You just forget to create the array that we are using for the spinner items. Please check the
Designing User Interface Part carefully.
Reply
Reply
Great turorial!
Thanks
Reply
can you give the coding how to view in another page not the same page.
Reply
The process is same.. Where you are stuck? You can check this youtube playlist
https://goo.gl/oqY7Bi
This may help you
Reply
hello mr belal, thank you for your tutorial, i really appreciate it, this tutorial is rally easy to understand, but
i have some question, i’m learning your code and because of my laziness i only make 2 attribute on my sql
table, just id and name, every operation is working fine, but when im insert data and try to update there’s
some error, it says
Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn’t match number
of bind variables in /home/faisal/Public/Web/android_sql_api/includes/DbOperation.php on line 24
case ‘insertData’:
//first check the parameters required for this request are available or not
availableParameters(array(‘name’));
if($result) {
//record is created means no error
$response[‘error’] = false;
} else {
break;
i’m on the test step and using Postman chrome app as you recommended, thank you, i really appreciate if
you want to help
Reply
In this line
$stmt->bind_param(“ssis”, $name);
you are using only a single string to bind so it should be
$stmt->bind_param(“s”, $name);
Reply
oh, thank you very much, in that case i’ll begin to learn for more, god bless you mr belal
Reply
how to use test this online mysql database. not getting any response from the dbconnect file
Reply
hello bilal,
I have issues with the PhP scripts ,the DbConnect.php Is returning an empty page without any message
Regards
Reply
Please help
Reply
Reply
Sir Belal, my add form is consist of 2 activities, how will I add it in the database if fields are divided in to
two activities.
If I had a chance to show you the activity, to make it clear.
Reply
Reply
Reply
Hi, i have a problem when i put the url on POST MAN showing this problem:
“error”: true,
“message”: “Parameters name, realname, rating, teamaffiliation missing”
Reply
Reply
I have a problem
error:
Reply
Reply