How to insert or add data to Android SQLite Database

When it comes to storing local data permanently in android application development, there are few options available.

We are going to look explore with simple code example how to insert or add data to android SQLite database.

Depending on the nature of the data, we can also use Shared Preference. Since Shared Preference is not part of what we will focus on you will leave it out.

But if you want to learn more about Shared Preference I will suggest you read our previous tutorial on Android SharedPreference example.

You can use or modify the sample code below rather than reinventing the wheel.

Android SQLite database API provides some helper classes (like SqLiteOpenHelper) which facilitates connecting your app with a database.

Below is the step upĀ  procedure

  1. Create a new SQLite database by extending the SqLiteOpenHelper. Override the onCreate() and onUpgrade()methods.
  2. Choose a name for your database file and all the columns your database will contain.
  3. Create a method that uses instance of ContentValues to add data to the created SQLite database

1. Create a new Java Class which extends SQLiteOpenHelper

In your android project, create a new Java class and name it DatabaseHelper.java. This class will extends SQLiteOpenHelper class and will override the onCreate() and onUpgrade() methods.

Inside the onCreate() method, we will create all the tables that will leave in our database while we will drop table in the onUpgrade() method.

The insert() method is a method we have created. Whenever it is call with a text parameter, we will store the content of the text in our database table.

Open the DatabaseHelper class and add the code below.

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "sqlite.db";

    public static final String TABLE_NAME = "dictionary";

    public static final String COL_ID = "_id";

    public static final String COL_2 = "word";

    SQLiteDatabase sqLiteDatabase;

    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null,2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DICTIONARY_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY," + COL_2 + " TEXT" + ")";
        db.execSQL(CREATE_DICTIONARY_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean insert(String text){
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, text);
        database.insert(TABLE_NAME, null, contentValues);
        return true;
    }
}

2. Open MainActivity class and its layout file

Open our default MainActivity XML layout file.

We are going to add an EditText and Button Views.

When a use adds some input to the EditText and click on the Button, we will retrieve the text content and store it in our SQLite database table.

Open the activity_main.xml file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".addDataToSQLite.MainActivity">


    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/user_input"
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/user_text_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter text" />
    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/save_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        android:background="#3F51B5"
        android:text="Save"
        android:textColor="#FFFFFF"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/user_input" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

Inside the MainActivity class, we are going to get the instances of our Views and also our database helper class.

Add the code below to the class. The code is simple and straight forward to understand

MainActivity.java

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.inducesmile.sqliteexample.R;
import com.inducesmile.sqliteexample.databaseHelper.DatabaseHelper;

import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private TextInputEditText userInput;

    private DatabaseHelper databaseHelper;


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

        setTitle("Add data to SQLite");

        databaseHelper = new DatabaseHelper(this);

        userInput = (TextInputEditText)findViewById(R.id.user_text_input);

        Button saveButton = (Button)findViewById(R.id.save_button);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = Objects.requireNonNull(userInput.getText()).toString();
                if(TextUtils.isEmpty(input)){
                    Toast.makeText(MainActivity.this, "Input field must be filled", Toast.LENGTH_SHORT).show();
                }

                boolean isSaved = databaseHelper.insert(input);
                if(isSaved){
                    Toast.makeText(MainActivity.this, "save successful", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MainActivity.this, "Error occurred while saving data", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

3. Let debug our database

If you have not used any android local database debug library, this is the time to use one.

We are going to make use of it in many other tutorials and code examples related to storing data locally in android.

Say hi to Android-Debug-Database library. You can read more about it from its Github page

Open build.gradle file and add the dependency below.

debugImplementation 'com.amitshekhar.android:debug-db:1.0.6'

4. Run your app

Click on the run button icon in Android Studio if you are using android studio.

If everything goes well, you will see and image like the screenshot below.

Add some text to the input field and click on the save button to see your added text content saved in the database.

Open the android debug database using the link provided from your android studio logcat. The local server will open a new browser page which will contain information the database and all its tables we have created.

The image below shows that text content that we added to the dictionary table.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.