Android App to Database
Android App to Database
database using HTTP requests, enabling communication with a server-side script that
1. Create a New Project: Open Android Studio and create a new project. Choose an
appropriate template
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
1. Choose a Database: Decide on a database. For this manual, as we have discussed in lab
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:
- 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
<?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'];
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
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.
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
pattern.
The permitAll() method allows all types of network operations (like HTTP
(ANR) errors.
By setting this policy, you are telling Android to permit network operations on
Important Note:
It may cause the app to freeze while waiting for network responses. But generally
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
8. Prepare Data: Use List<NameValuePair> to prepare data for the HTTP request
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.
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
HttpEntity entity=response.getEntity();
response content, as we discussed in lab session (e.g., PHP Script page, JSON
data).
InputStream is = entity.getContent();
The getContent method returns an InputStream that can be used to read the
response content.
(is) and converts them into characters using the specified character encoding
This specifies the buffer size for the BufferedReader, meaning it will use a
BY CHALEW Z. 7
StringBuffer(): This creates a new StringBuffer object, which is used to build
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).
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.
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).
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
BY CHALEW Z. 9