How to set up an SQL database in Android Studio

If you’re an Android Studio developer looking to set up an SQL database for your app, you’re in the right place. In this article, we’ll walk you through the process of setting up a SQLite database in Android Studio step by step. We’ll also cover best practices for managing and optimizing your database, so you can ensure that your app runs smoothly and efficiently.

What is SQL?

SQL, or Structured Query Language, is a standard language used to manage relational databases. It allows you to create, update, and query data in your database, as well as perform other operations like creating indexes and views.

Why Use SQL in Android Apps?

There are several reasons why you might want to use SQL in your Android app:

  • Storing and retrieving large amounts of data efficiently: SQLite databases are designed to handle large datasets, making them a great choice for apps that need to store and retrieve user data.
  • Ensuring data consistency: By using transactions and other SQL commands, you can ensure that your data is consistent and accurate, even when multiple users are accessing the same database at the same time.
  • Scalability: SQLite databases are highly scalable, which means you can easily add new tables or columns as your app grows and changes.

    Step 1: Create a New Project in Android Studio

    The first step to setting up an SQLite database is to create a new project in Android Studio. To do this, go to File > New > Project and select “Empty Activity”. Give your project a name and choose the minimum SDK version for your app.

    Step 2: Create a New SQLite Database File

    The next step is to create a new SQLite database file. To do this, open the DatabaseHelper class in your project and add the following code:

    java
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "myDatabase";
    public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS users (" +
    "id INTEGER PRIMARY KEY AUTOINCREMENT," +
    "name TEXT NOT NULL," +
    "email TEXT NOT NULL UNIQUE" +
    ");";
    db.execSQL(CREATE_TABLE);
    }
    }

In this code, we’re creating a new DatabaseHelper class that extends the SQLiteOpenHelper class. This helps us manage our database and ensures that it’s created properly when the app first runs. We’ve also defined a few constants: DATABASE_VERSION, which is used to keep track of changes to the database schema, and DATABASE_NAME, which is the name of our SQLite database file.

We’re also creating a table named users with columns for id, name, and email. The id column is set as the primary key and is automatically generated by Android.

Step 3: Create a Content Provider

Now that we have our database set up, we need to create a content provider that will allow us to access and manipulate the data in our database. To do this, open the ContentProvider class in your project and add the following code:

java
import android.content.ContentProvider;
import android.content.ContentValues;
import android.net.Uri;
public class UserContentProvider extends ContentProvider {
private static final String AUTHORITY = "com.example.android.userprovider";
private static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/users");
private static final String[] PROJECTION = {"id", "name", "email"};
@Override
public boolean onCreate() {
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder(getContext(), DatabaseHelper.DATABASE_NAME);
qb.setTables("users");
qb.setProjectionMap(projectionMapFromColumns(projection));
Cursor c = qb.query(DatabaseHelper.DATABASE_NAME, null, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
private Map<String, String> projectionMapFromColumns(String[] columns) {
Map<String, String> map = new HashMap<>();
for (String column : columns) {
if (column.contains(".")) {
String[] parts = column.split(".");
if (parts.length == 2) {
map.put(parts[0], parts[1]);
}
}
}
return map;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = new DatabaseHelper(getContext()).getWritableDatabase();

 Step 3: Create a Content Provider
long id = db.insert("users", null, values);
if (id > 0) {
Uri returnUri = ContentUris.withAppendedId(CONTENT_URI, id);
getContext().getContentResolver().notifyChange(returnUri, null);
return returnUri;
} else {
throw new SQLException("Failed to insert row into " + uri);
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final boolean needId = ContentUris.parseId(uri) != null;
if (needId || (selection == null && selectionArgs == null)) {
throw new IllegalArgumentException("Delete arguments are invalid");
}
SQLiteDatabase db = new DatabaseHelper(getContext()).getWritableDatabase();
int count = db.delete("users", selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final boolean needId = ContentUris.parseId(uri) != null;
if (needId || (selection == null && selectionArgs == null)) {
throw new IllegalArgumentException("Update arguments are invalid");
}
SQLiteDatabase db = new DatabaseHelper(getContext()).getWritableDatabase();
int count = db.update("users", values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
throw new UnsupportedOperationException("Method not yet implemented");
}
}

In this code, we’re registering our UserContentProvider class with the Android system using its fully qualified name (including the package name). We’re also setting the android:authorities attribute to a value that includes our app’s package name, which is used to uniquely identify our content provider.

Step 4: Test Our App

Now that everything is set up, we can test our app by creating a new user and inserting it into our database. To do this, open the main activity of your app and add some code to create a new UserContentProvider instance, create a new content value for the new user (name and email), and insert this data into our database using the content provider:

java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.ContentValues;
import android.net.Uri;
import com.example.android.userprovider.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new content provider instance
UserContentProvider userProvider = new UserContentProvider();
// Create a new content value for the new user
ContentValues values = new ContentValues();
values.put("name", "John Doe");
values.put("email", "johndoe@example.com");
// Insert the new user into the database using the content provider
Uri uri = userProvider.insert(UserContentProvider.CONTENT_URI, values);
System.out.println("New user inserted with ID: " + uri.getLastPathSegment());
}
}

That’s it! You now have a basic SQLite database set up in your Android app with a content provider to access and manipulate the data.