Sunteți pe pagina 1din 54

Simplified Coding

About
Contact Us
Advertise
Privacy Policy

Home » Android MySQL Tutorial to Perform Basic CRUD Operation

Android MySQL Tutorial to Perform Basic CRUD Operation


October 24, 2015 by Belal Khan 57 Comments

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.

Creating a Record -> In the database we insert a record.


Reading Stored Records -> No point of saving data when we can’t read it back 😛 (LOL). So the second
operation is reading the stored data back.
Updating Stored Records -> We may also need to update the existing data. So the third operation is
update.
Deleting Records -> Lastly we may also need to delete the existing data from the database.

So basically in any database we perform the above mentioned operations. In this tutorial I am going to use
MySQL and PHP.

Why PHP and MySQL and Why Not SQLite?


Android gives us a feature of SQLite to use as the RDBMS for our app. But we can’t use SQLite only if we are
building an app. This is because we need a centralize server. SQLite is local for every device so if a user is using
your application you will not be able manage your users if it is only in SQLite. That is why we need a centralize
database where we can store our app data.

Do we have only PHP and MySQL for this?

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.

Building Web APIs


The first step is building the required Web APIs. This is because from the android application, to communicate
with our web server we need an interface called API.

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

1 -- created by Belal Khan


2 -- website: www.simplifiedcoding.net
3 -- tables
4 -- Table: heroes
5 CREATE TABLE heroes (
6 id int NOT NULL AUTO_INCREMENT,
7 name varchar(200) NOT NULL,
8 realname varchar(200) NOT NULL,
9 rating int NOT NULL,
10 teamaffiliation varchar(100) NOT NULL,
11 CONSTRAINT heroes_pk PRIMARY KEY (id)
12 );
13
14 -- End of file.

Creating PHP Project

Now to perform the Database Operations we will create a PHP Project.

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).

php project structure

You see we have four php files (3 inside includes and 1 inside v1). So you create these files as well.

Project Structure

So we have the following things in our PHP project.


includes
Constants.php: In this file we will define all the required constants e.g., database name,
username, password etc.
DbConnect.php: This fill will contain a class where we will connect to our MySQL
database.
DbOperation.php: The actual CRUD operation is performed inside this file.
v1
Api.php: This is our API, we will send request to this file only from the android side. And
this file will handle all the API calls.

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

Performing Database Operations

Now we will do the CRUD operation inside the DbOperation.php file.

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

Handling API Calls

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

Now lets test the APIs.

Testing the API Calls

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.

Finalizing API Calls

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.

URL Method Parameter


name, realname, rating,
http://192.168.101.1/HeroApi/v1/Api.php?apicall=createhero POST
teamaffiliation
http://192.168.101.1/HeroApi/v1/Api.php?apicall=getheroes GET
http://192.168.101.1/HeroApi/v1/Api.php?apicall=updatehero POST id, name, realname, rating,
teamaffiliation
http://192.168.101.1/HeroApi/v1/Api.php?
GET
apicall=deletehero&id=idvalue

Android MySQL Tutorial


We have our Web Services, and now we can build the android application. So lets start.

Creating a new Project

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.

Creating Helper Classes

Class To Store API URLs

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 }

Hero Model Class

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 }

Defining Internet Permission in AndroidManifest


As we need to perform network request from our Application, we need to define internet permission for
this. So define it in your AndroidManifest.xml as below.

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>

Designing User Interface


The below image shows how our final application will look.
Application UI

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"?>

1 <?xml version="1.0" encoding="utf-8"?>


2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:tools="http://schemas.android.com/tools"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent"
6 tools:context="net.simplifiedlearning.myheroapp.MainActivity">
7
8 <LinearLayout
9 android:id="@+id/linearLayout"
10 android:layout_width="match_parent"
11 android:layout_height="wrap_content"
12 android:layout_alignParentTop="true"
13 android:orientation="vertical"
14 android:padding="16dp">
15
16 <EditText
17 android:id="@+id/editTextHeroId"
18 android:layout_width="match_parent"
19 android:layout_height="wrap_content"
20 android:visibility="gone" />
21
22 <EditText
23 android:id="@+id/editTextName"
24 android:layout_width="match_parent"
25 android:layout_height="wrap_content"
26 android:layout_marginBottom="8dp"
27 android:layout_marginTop="8dp"
28 android:hint="Name" />
29
30 <EditText
31 android:id="@+id/editTextRealname"
32 android:layout_width="match_parent"
33 android:layout_height="wrap_content"
34 android:layout_marginBottom="8dp"
35 android:layout_marginTop="8dp"
36 android:hint="Realname" />
37
38
39 <RatingBar
40 android:id="@+id/ratingBar"
41 android:layout_width="wrap_content"
42 android:layout_height="wrap_content"
43 android:numStars="5"
44 android:stepSize="1" />
45
46 <Spinner
47 android:id="@+id/spinnerTeamAffiliation"
48 android:layout_width="match_parent"
49 android:layout_height="wrap_content"
50 android:layout_marginBottom="8dp"
51 android:layout_marginTop="8dp"
52 android:entries="@array/teams" />
53
54
55 <Button
56 android:id="@+id/buttonAddUpdate"
57 android:layout_width="match_parent"
58 android:layout_height="wrap_content"
59 android:text="Add" />
60 </LinearLayout>
61
62 <ListView
63 android:id="@+id/listViewHeroes"
64 android:layout_width="match_parent"
65 android:layout_height="wrap_content"
66 android:layout_below="@id/linearLayout" />
67
68 <ProgressBar
69 android:id="@+id/progressBar"
70 android:layout_width="wrap_content"
71 android:layout_height="wrap_content"
72 android:layout_centerHorizontal="true"
73 android:layout_centerVertical="true"
74 android:visibility="gone" />
75
76 </RelativeLayout>

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.

Class to Perform Network Request


The point is we cannot directly perform a network request in the application’s main thread. So for this we
need an AsyncTask to perform the task in a separate thread. Hence we will create an inner class inside
MainActivity.java.

Java

//inner class
to perform network

1 //inner class to perform network request extending an AsyncTask


2 private class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
3
4 //the url where we need to send the request
5 String url;
6
7 //the parameters
8 HashMap<String, String> params;
9
10 //the request code to define whether it is a GET or POST
11 int requestCode;
12
13 //constructor to initialize values
14 PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
15 this.url = url;
16 this.params = params;
17 this.requestCode = requestCode;
18 }
19
20 //when the task started displaying a progressbar
21 @Override
22 protected void onPreExecute() {
23 super.onPreExecute();
24 progressBar.setVisibility(View.VISIBLE);
25 }
26
27
28 //this method will give the response from the request
29 @Override
30 protected void onPostExecute(String s) {
31 super.onPostExecute(s);
32 progressBar.setVisibility(GONE);
33 try {
34 JSONObject object = new JSONObject(s);
35 if (!object.getBoolean("error")) {
36 Toast.makeText(getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
37 //refreshing the herolist after every operation
38 //so we get an updated list
39 //we will create this method right now it is commented
40 //because we haven't created it yet
41 //refreshHeroList(object.getJSONArray("heroes"));
42 }
43 } catch (JSONException e) {
44 e.printStackTrace();
45 }
46 }
47
48 //the network operation will be performed in background
49 @Override
50 protected String doInBackground(Void... voids) {
51 RequestHandler requestHandler = new RequestHandler();
52
53 if (requestCode == CODE_POST_REQUEST)
54 return requestHandler.sendPostRequest(url, params);
55
56
57 if (requestCode == CODE_GET_REQUEST)
58 return requestHandler.sendGetRequest(url);
59
60 return null;
61 }
62 }

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

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
7 //defining views
8 EditText editTextHeroId, editTextName, editTextRealname;
9 RatingBar ratingBar;
10 Spinner spinnerTeam;
11 ProgressBar progressBar;
12 ListView listView;
13 Button buttonAddUpdate;
14
15
16 //we will use this list to display hero in listview
17 List<Hero> heroList;
18
19 //as the same button is used for create and update
20 //we need to track whether it is an update or create operation
21 //for this we have this boolean
22 boolean isUpdating = false;
23
24
25 @Override
26 protected void onCreate(Bundle savedInstanceState) {
27 super.onCreate(savedInstanceState);
28 setContentView(R.layout.activity_main);
29
30 editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
31 editTextName = (EditText) findViewById(R.id.editTextName);
32 editTextRealname = (EditText) findViewById(R.id.editTextRealname);
33 ratingBar = (RatingBar) findViewById(R.id.ratingBar);
34 spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);
35
36 buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
37
38 progressBar = (ProgressBar) findViewById(R.id.progressBar);
39 listView = (ListView) findViewById(R.id.listViewHeroes);
40
41 heroList = new ArrayList<>();
42
43
44 buttonAddUpdate.setOnClickListener(new View.OnClickListener() {
45 @Override
46 public void onClick(View view) {
47 //if it is updating
48 if (isUpdating) {
49 //calling the method update hero
50 //method is commented becuase it is not yet created
51 //updateHero();
52 } else {
53 //if it is not updating
54 //that means it is creating
55 //so calling the method create hero
56 createHero();
57 }
58 }
59 });
60
61 //calling the method read heroes to read existing heros from the database
62 //method is commented because it is not yet created
63 //readHeroes();
64 }

Now we need to create the method createHero().

Java

private void
createHero() {

1 private void createHero() {


2 String name = editTextName.getText().toString().trim();
3 String realname = editTextRealname.getText().toString().trim();
4
5 int rating = (int) ratingBar.getRating();
6
7 String team = spinnerTeam.getSelectedItem().toString();
8
9
10 //validating the inputs
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 //if validation passes
24
25 HashMap<String, String> params = new HashMap<>();
26 params.put("name", name);
27 params.put("realname", realname);
28 params.put("rating", String.valueOf(rating));
29 params.put("teamaffiliation", team);
30
31
32 //Calling the create hero API
33 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_CREATE_HERO, params,
34 CODE_POST_REQUEST);
35 request.execute();
}

Now run the application and try adding a new hero.


Android MySQL – Create Operation

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

Create a layout resource file named layout_hero_list.xml.

layout_hero_list.xml
<?xml version="1.0"
encoding="utf-8"?>

1 <?xml version="1.0" encoding="utf-8"?>


2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="horizontal"
6 android:padding="8dp">
7
8
9 <TextView
10 android:id="@+id/textViewName"
11 android:layout_width="wrap_content"
12 android:layout_height="wrap_content"
13 android:layout_alignParentLeft="true"
14 android:layout_weight="8"
15 android:text="Captain America"
16 android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
17
18
19 <TextView
20 android:textStyle="bold"
21 android:id="@+id/textViewUpdate"
22 android:layout_width="wrap_content"
23 android:layout_height="wrap_content"
24 android:layout_alignBottom="@+id/textViewDelete"
25 android:layout_toLeftOf="@+id/textViewDelete"
26 android:layout_toStartOf="@+id/textViewDelete"
27 android:padding="5dp"
28 android:text="Update"
29 android:textColor="#498C1A" />
30
31 <TextView
32 android:textStyle="bold"
33 android:id="@+id/textViewDelete"
34 android:layout_width="wrap_content"
35 android:layout_height="wrap_content"
36 android:layout_alignParentRight="true"
37 android:padding="5dp"
38 android:text="Delete"
39 android:textColor="#C20A10" />
40
41 </RelativeLayout>
Custom Adapter Class

Create one more inner class inside MainActivity class. We will name it HeroAdapter.

HeroAdapter
Java
class HeroAdapter
t d

1 class HeroAdapter extends ArrayAdapter<Hero> {


2
3 //our hero list
4 List<Hero> heroList;
5
6
7 //constructor to get the list
8 public HeroAdapter(List<Hero> heroList) {
9 super(MainActivity.this, R.layout.layout_hero_list, heroList);
10 this.heroList = heroList;
11 }
12
13
14 //method returning list item
15 @Override
16 public View getView(int position, View convertView, ViewGroup parent) {
17 LayoutInflater inflater = getLayoutInflater();
18 View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);
19
20 //getting the textview for displaying name
21 TextView textViewName = listViewItem.findViewById(R.id.textViewName);
22
23 //the update and delete textview
24 TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
25 TextView textViewDelete = listViewItem.findViewById(R.id.textViewDelete);
26
27 final Hero hero = heroList.get(position);
28
29 textViewName.setText(hero.getName());
30
31 //attaching click listener to update
32 textViewUpdate.setOnClickListener(new View.OnClickListener() {
33 @Override
34 public void onClick(View view) {
35 //so when it is updating we will
36 //make the isUpdating as true
37 isUpdating = true;
38
39 //we will set the selected hero to the UI elements
40 editTextHeroId.setText(String.valueOf(hero.getId()));
41 editTextName.setText(hero.getName());
42 editTextRealname.setText(hero.getRealname());
43 ratingBar.setRating(hero.getRating());
44 spinnerTeam.setSelection(((ArrayAdapter<String>) spinnerTeam.getAdapter()).getPosition(hero.getTeamaffiliation()));
45
46 //we will also make the button text to Update
47 buttonAddUpdate.setText("Update");
48 }
49 });
50
51 //when the user selected delete
52 textViewDelete.setOnClickListener(new View.OnClickListener() {
53 @Override
54 public void onClick(View view) {
55
56 // we will display a confirmation dialog before deleting
57 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
58
59 builder.setTitle("Delete " + hero.getName())
60 .setMessage("Are you sure you want to delete it?")
61 .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
62 public void onClick(DialogInterface dialog, int which) {
63 //if the choice is yes we will delete the hero
64 //method is commented because it is not yet created
65 //deleteHero(hero.getId());
66 }
67 })
68 .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
69 public void onClick(DialogInterface dialog, int which) {
70 }
71 })
72 .setIcon(android.R.drawable.ic_dialog_alert)
73 .show();
74
75 }
76 });
77
78 return listViewItem;
79 }
80 }
Retrieving Heroes from the Database

Create a method named readHeroes().

readHeroes()
Java
private void
readHeroes() {

1 private void readHeroes() {


2 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_HEROES, null, CODE_GET_REQUEST);
3 request.execute();
4 }

Now one more method we need to refresh the Hero List. So create a method named refreshHeroList().

refreshHeroList()
Java
private void
refreshHeroList(JSO

1 private void refreshHeroList(JSONArray heroes) throws JSONException {


2 //clearing previous heroes
3 heroList.clear();
4
5 //traversing through all the items in the json array
6 //the json we got from the response
7 for (int i = 0; i < heroes.length(); i++) {
8 //getting each hero object
9 JSONObject obj = heroes.getJSONObject(i);
10
11 //adding the hero to the list
12 heroList.add(new Hero(
13 obj.getInt("id"),
14 obj.getString("name"),
15 obj.getString("realname"),
16 obj.getInt("rating"),
17 obj.getString("teamaffiliation")
18 ));
19 }
20
21 //creating the adapter and setting it to the listview
22 HeroAdapter adapter = new HeroAdapter(heroList);
23 listView.setAdapter(adapter);
24 }
Now also uncomment the commented method inside PeformNetworkRequest class and onCreate()
method. You need to uncomment readHeroes() inside onCreate() and refreshHeroList() inside
PerformNetworkRequest class.
Now you can try running the application.

Android MySQL – Read Operation

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.

Android MySQL – Update Operation

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)

1 private void deleteHero(int id) {


2
3 PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_DELETE_HERO + id, null,
4 CODE_GET_REQUEST);
request.execute();
}

Now uncomment the method deleteHero() inside the HeroAdapter class.


And lets test the delete operation as well.

Android MySQL – Delete Operation

So it is working fine as well. And we have done with all the basic CRUD operations.

The complete code for MainActivity

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.

Android MySQL Tutorial

Android MySQL Tutorial

Android MySQL Tutorial – Source Code Download


If you are still facing troubles you can get my source code from below. It has everything, the server side
scripts, database file and android project.
So thats all for this Android MySQL Tutorial friends. CRUD Operation is needed in almost every application so
it is a very important thing. If you are having any confusions or queries regarding this Android MySQL tutorial
don’t hesitate in asking on comments. And if you liked the post then PLEASE SHARE IT. Thank You 🙂

Sharing is Caring:

Tweet

More

Related

Some more tutorials for you

1. Login With Facebook Android Studio using Facebook SDK 4


2. Android SMS Verification App – Phone Verification with OTP
3. Android Custom GridView with Images and Texts using Volley
4. Android Firebase Tutorial – User Registration with Authentication
5. Android Game Development Tutorial – Simple 2d Game Part 2
6. Video Call Android Tutorial – Implementing Video Call using Sinch

Subscribe To Our Newsletter

Subscribe To Our Newsletter


Join our mailing list to receive the latest news and updates from our team.

Email
SUBSCRIBE!

You have Successfully Subscribed!


Filed Under: Android Advance, Android Application Development Tagged With: android app mysql, android
connect to mysql, android mysql, android mysql tutorial

About Belal Khan

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

1. LEE CHEE PHANG says

October 28, 2015 at 8:30 am

This is great ! Thanks author, i really like your post so much and it is up to date… Thumbs UP !

Reply

2. PRATHAP says

October 28, 2015 at 12:51 pm

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

October 29, 2015 at 8:32 am

Awesome tutorial !! Thank you Belal !!

Reply

4. Kevien says

October 29, 2015 at 8:34 am

Thanks a lot.great one!!really easy to understand for beginner.

Reply

5. Renan Marcos da Silva says

April 8, 2016 at 12:41 am

AMAZING BRO! Thank you so much, you really help me!


Reply

6. laxmi says

June 23, 2016 at 6:56 am

Hi Mr.Belal ,this is very much helpful ,thank you so much for this awesome tutorial.

Reply

7. reza says

June 24, 2016 at 3:00 pm

hi , its so helping me!,


all code above, work so well, thank you
cheers!

Reply

8. Amit says

September 5, 2016 at 5:29 am

Awesome Stuff a big help!!!

Reply

9. Ahmad Atho' Miftahuddin says

November 21, 2016 at 2:33 pm

Thank You very much, this is working

Reply

10. Jack77 says

December 7, 2016 at 1:43 am

Just want to say you rock man!


Thank you very much for this tutorial, other tutorial use some depecrated class, but this one is up-to-date!

Reply

11. Ashish says

December 21, 2016 at 8:07 am

Amazing !!! great job… Never failed to surprise me for running program without error. Keep it up . Best
Tut…

Reply

12. Vino says

December 28, 2016 at 6:29 am


Thank you so much ! Helped a lot !

Reply

13. BENDEK says

May 14, 2017 at 1:14 am

GREAT TUTORIAL, VERY USEFUL…THANKS

Reply

14. wan says

August 26, 2017 at 6:30 pm

Hi Belal,
Thanks for the tutorial.
the tutorial very easy to understands.Thanks man

Reply

15. Romahdon Akbar Sholeh says

September 12, 2017 at 2:19 am

woow Thanks Brother Amazing …..

Reply

16. vikas yadav says

September 14, 2017 at 8:41 am

can’t connect to mysql and inesrt to data


so please help me

Reply

Sagar Mahewar says

September 16, 2017 at 2:19 pm

Hello VikasYadav, what error its showing, can you share details ?

Reply

17. Elise Marchis says

September 16, 2017 at 12:43 am

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?

WIN7 / 64 / ANDROID STUDIO ver 2.3.3

thanks

Reply

Belal Khan says

September 17, 2017 at 3:06 am

You just forget to create the array that we are using for the spinner items. Please check the
Designing User Interface Part carefully.

Reply

Elise Marchis says

September 19, 2017 at 9:41 pm

Thanks. Works!! Great post. It helped a lot.

Reply

18. Siegfried says

September 18, 2017 at 7:11 pm

Great turorial!

I’m using this example for creating my own project.


Only i’m using Volley.

The problem is that i get an ‘Invalid API call’ error message.


How do i pass the ‘apicall’ to the php-file? Map getParams?

Thanks

Reply

19. umi says

September 19, 2017 at 5:48 am

can you give the coding how to view in another page not the same page.

Reply

Belal Khan says

September 19, 2017 at 5:51 am

The process is same.. Where you are stuck? You can check this youtube playlist
https://goo.gl/oqY7Bi
This may help you
Reply

20. Indrawan Faisal says

September 21, 2017 at 12:50 pm

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

And Heres Line 24 on my DbOperation File

21. //Create operation


22. function insertData($name) {
23. $stmt = $this->con->prepare(“INSERT INTO myTable (name) VALUES (?)”);
24. $stmt->bind_param(“ssis”, $name);
25. if($stmt->execute())
26. return true;
27. return false;
28. }

And This is My Insert Case on main php

case ‘insertData’:

//first check the parameters required for this request are available or not
availableParameters(array(‘name’));

//create a new operation object


$db = new DbOperation();

//create a record by call insert method


$result = $db->insertData(
$_POST[‘name’]
);

//if the record is created adding success to response

if($result) {
//record is created means no error
$response[‘error’] = false;

//in message we have a success message


$response[‘message’] = ‘Record added successfully’;

//reload the data


$response[‘data’] = $db->getData();

} else {

//if record is not added that means there is an error


$response[‘error’] = true;
//and we have error message
$response[‘message’] = ‘some error occurred, please try again’;

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

sorry for english

Reply

Belal Khan says

September 22, 2017 at 3:51 am

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

Indrawan Faisal says

September 23, 2017 at 5:15 am

oh, thank you very much, in that case i’ll begin to learn for more, god bless you mr belal

Reply

21. jordan says

September 24, 2017 at 5:11 pm

how to use test this online mysql database. not getting any response from the dbconnect file

Reply

22. jordan says

September 26, 2017 at 10:42 pm

hello bilal,

I have issues with the PhP scripts ,the DbConnect.php Is returning an empty page without any message

Regards

Reply

23. Napster says

September 29, 2017 at 7:49 pm


i get this error when i try to run the app

Error:(98, 70) Gradle: error: URL_CREATE_HERO has private access in Api


Error:(103, 70) Gradle: error: URL_READ_HEROES has private access in Api
Error:(137, 70) Gradle: error: URL_UPDATE_HERO has private access in Api
Error:(151, 70) Gradle: error: URL_DELETE_HERO has private access in Api

Please help

Reply

Belal Khan says

September 30, 2017 at 4:54 am

Make these constants public by adding public keyword on each line..

Reply

24. Joleth Catama says

October 13, 2017 at 11:30 pm

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

25. Joleth Catama says

October 13, 2017 at 11:31 pm

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn’t match


number of bind variables in
C:\xampp\htdocs\www\includes\dboperations.php on line
28

{“error”:true,”message”:”Some error occurred please try again”}

Can you help me?

Reply

Joleth Catama says

October 13, 2017 at 11:45 pm

oh, no need. thanks.

Reply

26. Joleth Catama says

October 16, 2017 at 3:50 pm

I copied everything here, to have a sample app. But it doesn’t work. :3


Reply

27. diego says

October 20, 2017 at 2:57 pm

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”

what could it means? i nwe in android, please helpppp D:

Reply

Belal Khan says

October 22, 2017 at 7:28 am

Please check the video that I embedded in this post. 🙂

Reply

28. Nishan says

October 30, 2017 at 5:54 am

I have a problem

error:

JSONException: Value Connection of type java.lang.String cannot be converted to JSONObject

Reply

29. vishal says

November 9, 2017 at 11:14 am

Hello sir,This is really great tutorial.


I want to insert table data in thai language and retrive it in same.
i am able to insert data in thai language but unable to get response in thai.
any solution??

Reply

30. asn says

November 17, 2017 at 6:48 am

AoA, hi i have Coppied every thing in a sample project, but i am getting


{“error”:true,”message”:”Invalid API Call”}
this when i run API.php

kindly tell me what is this where is API calling.


P.S em newbie to PHP and andriod.

S-ar putea să vă placă și