Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Connecting Android Studio to MySQL Database

Tech May 13 1

To establsih a connection between Android Studio and a MySQL database, follow these steps:

First, ensure that the MySQL server allows remote connections. If you encounter connection issues, verify that the root user password has been updated correctly. Referencing external documentation can help resolve common problems.

Create a new Android project and add the MySQL JDBC driver to your project's libs directory. Make sure to use the correct version of the JAR file ending with -bin.

Add the JAR file as a library in your project settings to enable access to database functionalities.

Implement a helper class for database operations:

package com.example.login.helper;

import com.mysql.jdbc.Connection;

import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnector {
    private static final String DATABASE_URL = "jdbc:mysql://your_host:3306/login";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "your_password";

    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = (Connection) DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

In your main activity, implement login functionality using a background thread to handle database queries:

package com.example.login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.login.helper.DatabaseConnector;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginActivity extends AppCompatActivity {
    private EditText usernameField, passwordField;
    private TextView registerLink, logoutLink;
    private Button loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameField = findViewById(R.id.username);
        passwordField = findViewById(R.id.password);
        registerLink = findViewById(R.id.register_link);
        logoutLink = findViewById(R.id.logout_link);
        loginButton = findViewById(R.id.login_button);

        loginButton.setOnClickListener(v -> new Thread(() -> {
            Connection dbConnection = DatabaseConnector.getConnection();
            String query = "SELECT * FROM userinfo WHERE uname=? AND psw=?";
            try {
                PreparedStatement statement = (PreparedStatement) dbConnection.prepareStatement(query);
                statement.setString(1, usernameField.getText().toString());
                statement.setString(2, passwordField.getText().toString());
                ResultSet result = statement.executeQuery();
                Looper.prepare();
                if (result.next()) {
                    Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }).start());

        registerLink.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
        logoutLink.setOnClickListener(v -> startActivity(new Intent(this, LogoutActivity.class)));
    }
}

Design the layout for the login screen in activity_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="Login"
        android:textStyle="bold"
        android:layout_gravity="center" />

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter username"
        android:paddingLeft="10dp" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter password"
        android:paddingLeft="10dp" />

    <Button
        android:id="@+id/login_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login" />

    <TextView
        android:id="@+id/register_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register"
        android:textSize="17sp"
        android:layout_gravity="center" />

    <TextView
        android:id="@+id/logout_link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:textSize="17sp"
        android:layout_gravity="center" />

</LinearLayout>

For registration, create a second actiivty with similar logic:

package com.example.login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.login.helper.DatabaseConnector;
import com.mysql.jdbc.PreparedStatement;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RegisterActivity extends AppCompatActivity {
    private EditText usernameField, passwordField;
    private Button registerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        usernameField = findViewById(R.id.username);
        passwordField = findViewById(R.id.password);
        registerButton = findViewById(R.id.register_button);

        registerButton.setOnClickListener(v -> new Thread(() -> {
            Connection dbConnection = DatabaseConnector.getConnection();
            String checkQuery = "SELECT * FROM userinfo WHERE uname=?";
            try {
                PreparedStatement checkStatement = (PreparedStatement) dbConnection.prepareStatement(checkQuery);
                checkStatement.setString(1, usernameField.getText().toString());
                ResultSet result = checkStatement.executeQuery();
                Looper.prepare();
                if (result.next()) {
                    Toast.makeText(RegisterActivity.this, "Username already exists", Toast.LENGTH_SHORT).show();
                } else {
                    String insertQuery = "INSERT INTO userinfo(uname, psw) VALUES (?, ?)";
                    PreparedStatement insertStatement = (PreparedStatement) dbConnection.prepareStatement(insertQuery);
                    insertStatement.setString(1, usernameField.getText().toString());
                    insertStatement.setString(2, passwordField.getText().toString());
                    int rowsAffected = insertStatement.executeUpdate();
                    runOnUiThread(() -> {
                        if (rowsAffected > 0) {
                            Toast.makeText(RegisterActivity.this, "Registration successful", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                Looper.loop();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }).start());
    }
}

The registration layout should be defined in activity_register.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="Register"
        android:textStyle="bold"
        android:layout_gravity="center" />

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter username"
        android:paddingLeft="10dp" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter password"
        android:paddingLeft="10dp" />

    <Button
        android:id="@+id/register_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register" />

</LinearLayout>

Finally, update the AndroidManifest.xml file to include all newly created activities:

<activity
    android:name=".LoginActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity
    android:name=".RegisterActivity"
    android:exported="false" />
<activity
    android:name=".LogoutActivity"
    android:exported="false" />

Ensure that network permissions are granted in the manifest for internet access required by the database connection.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.