This comprehensive guide outlines the steps to connect an Android application to a
database using HTTP requests, enabling communication with a server-side script that
manages database interactions
Step 1: Set Up Your Development Environment
1. Create a New Project: Open Android Studio and create a new project. Choose an
appropriate template
2. Set Permissions: Add internet permissions to your AndroidManifest.xml to allow
network communication:
3. Add Dependencies: If you are using Android 6.0 (API level 23) or higher, consider
using libraries for network operations. For basic HTTP requests, you can use Apache
HttpClient or URLConnection in your build.gradle Module app file.
Step 2: Set Up Your Database
1. Choose a Database: Decide on a database. For this manual, as we have discussed in lab
session you are using MySQL.
2. Create a Database: Use a database management tool (like phpMyAdmin) to create a new
database and table. For example, create a database called android and a table stud with
fields:
- ID (VARCHAR, PRIMARY KEY)
- Fname (VARCHAR)
- Lname (VARCHAR)
- Gender (VARCHAR)
BY CHALEW Z. 1
3. Create a Server-side Script: Write a server-side script (e.g., PHP) to handle incoming
requests and interact with the database. Here’s a simple example:
<?php
$hostname_localhost ="localhost";
$database_localhost ="android";
$username_localhost ="root";
$password_localhost ="";
$con=mysqli_connect($hostname_localhost,$username_localhost,$password_localhost)ortrigger
_error(mysqli_error(), E_USER_ERROR);
mysqli_select_db($con, $database_localhost);
$id = $_POST['ID'];
$fname = $_POST['Fname'];
$lname = $_POST['Lname'];
$gender = $_POST['Gender'];
$q = "SELECT * FROM stud WHERE ID = '$id'";
$result = mysqli_query($con, $q);
if (mysqli_num_rows($result) == 0) {
$Sql_Query = "INSERT INTO stud (ID, Fname, Lname, Gender) VALUES ('$id', '$fname',
'$lname', '$gender')";
if (mysqli_query($con, $Sql_Query)) {
$response = 'Account created!!';
echo json_encode($response);
} else {
echo "Please try again";
} } else {
echo "User ID already exists, please try another";
}
mysqli_close($con);
?>
BY CHALEW Z. 2
Step 3: Set Up the Android Application
1. Create UI Elements: In your activity_main.xml, create UI elements such as EditText
for input fields and Button for submission:
<EditText android:id="@+id/uid" ... />
<EditText android:id="@+id/fname" ... />
<EditText android:id="@+id/lname" ... />
<Spinner android:id="@+id/gender" ... />
<Button android:id="@+id/register" ... />
Step 4: Implement Network Communication in Your Activity
1. Defines the MainActivity class, which extends AppCompatActivity, allowing it to use
features from the Android support library.
2. Declares UI components (buttons, spinner, edit texts) and variables for storing
results and input streams. The ip variable holds the server's IP address.
Button send; Spinner gender;
EditText fname, lname, id; String result = null; String line = null;
InputStream is;
String ip = "192.168.1.2";
3. Overrides the onCreate method, which is called when the activity is created. And
Sets the content view to the specified layout resource.
BY CHALEW Z. 3
4. Sets a policy that allows network operations on the main thread
This line creates a new StrictMode.ThreadPolicy object using the builder
pattern.
The permitAll() method allows all types of network operations (like HTTP
requests) on the main thread. By default, such operations would be blocked to
avoid potential performance problems, such as "Application Not Responding"
(ANR) errors.
By setting this policy, you are telling Android to permit network operations on
the main thread.
Important Note:
It may cause the app to freeze while waiting for network responses. But generally
recommended to perform network operations on a background thread using
AsyncTask, Thread, or other concurrency mechanisms in Android.
5. Initialize UI Components: In your MainActivity.java, link the UI elements to their
IDs:
BY CHALEW Z. 4
6. Set Up Button Click Listener: Implement an OnClickListener for the submit button:
7. Validate Input: Before sending data, validate each input field to ensure they are not
empty and meet criteria.
8. Prepare Data: Use List<NameValuePair> to prepare data for the HTTP request
containing the user data.
This line initializes a new list called nvp that will store key-value pairs, which
represent the data to be sent to the server. The integer argument (1) is an
initial capacity hint, which is not mandatory but can optimize memory usage.
BY CHALEW Z. 5
These lines add data to the nvp list as BasicNameValuePair objects.
new BasicNameValuePair("ID", id1): Creates a key-value pair where "ID" is the
key and id1 (user ID) is the value.
Similarly for "Fname", "Lname", and "Gender", the respective values are added
from the user input.
9. Initializes an HTTP client and prepares a POST request to the specified URL,
attaching the name-value pairs as the request or to send the data to the server.
The URL points to the server-side PHP script that will handle the incoming data.
The variable ip holds the server's IP address.
UrlEncodedFormEntity ensures that special characters are encoded in a way
that can be safely transmitted over HTTP.
10. Executes the POST request and retrieves the response entity content.
BY CHALEW Z. 6
Detail Explanation of this three lines of code:
HttpResponse response=client.execute(post);
This line executes the HTTP POST request (post) using the HTTP client (client).
The execute method sends the request to the server and returns an
HttpResponse object that contains the server's response.
HttpEntity entity=response.getEntity();
This line retrieves the entity or body of the HTTP response.
The getEntity method returns an HttpEntity object that represents the
response content, as we discussed in lab session (e.g., PHP Script page, JSON
data).
InputStream is = entity.getContent();
This line gets the content of the HttpEntity as an InputStream.
The getContent method returns an InputStream that can be used to read the
response content.
11. Read Response: Capture the server's response
This creates an InputStreamReader that reads bytes from the InputStream
(is) and converts them into characters using the specified character encoding
("ISO-8859-1"). NB: you can use “UTF-8” instead of "ISO-8859-1"
This specifies the buffer size for the BufferedReader, meaning it will use a
buffer with a capacity of 8 characters.
BY CHALEW Z. 7
StringBuffer(): This creates a new StringBuffer object, which is used to build
a string by appending characters read from the BufferedReader.
12. Reading and Appending:
The while loop reads each line from the BufferedReader until the end of the
stream is reached (readLine() returns null when there are no more lines to read).
Each line is appended to the StringBuilder (sb).
13. Converting StringBuffer to String and Displays the server response
After all lines have been appended to the StringBuilder, the toString() method
convert the content into a String and assigns it to the result variable.
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
This line creates and shows a Toast message that displays the result string. The Toast
is shown in the MainActivity context and remains visible for a long duration
(Toast.LENGTH_LONG).
Step 5: Testing Stage
1. Run the Application: Connect your Android device or use an emulator, and run the
application.
BY CHALEW Z. 8
2. Enter Data: Fill in the input fields and click the submit button.
3. Check Database: Verify that the data is correctly inserted into the database by
checking via your database management tool.
BY CHALEW Z. 9