Insert data into SQLite database in Android, SQLite is an open source embedded database. SQLite is one of the most widely deployed databases in the world. SQLite database is mainly used in Smartphone operating Systems like IOS, Android etc. Android SQLite database has three main Classes. Here we will learn SQLite database tutorial in Android so let’s start…

Wants to Learn Android application development from the scratch  ?

  • SQLiteOpenHelper Class
  • SQLiteDatabase Class
  • SQLiteCursor Class

SQLiteOpenHelper Class: – SQLiteOpenHelper class has mainly two methods  onCreate and onUpgrade. onCreate method is used to create the table. onUpgrade method is used to upgrade the database.

SQLiteDatabase class: – SQLiteDabase is used to open the database either in readable or writable form. it has two methods

Writable form

// writable form

SQLiteDatabase db = this.getWritableDatabase();

Readable form

// Readable form

SQLiteDatabase db = this.getReadableDatabase();

SQLiteCursor Class: – SQLiteCursor class is used to iterate the table.

Insert the data into SQLite database in Android: –

  1. Create a project in Android studio name it Mydatabase. now create a signup.xml file(res>layout>signup.xml).

signup.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/snack"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradiant">






    <ImageView
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/rleftbutton"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="20dp"
        android:layout_marginBottom="15dp"
        />





    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_centerInParent="true"
        android:layout_below="@+id/logo"
        android:layout_marginTop="30dp">

        <EditText
            android:id="@+id/etname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Name"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"

            ></LinearLayout>

        <EditText
            android:id="@+id/etemail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Email"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"
            ></LinearLayout>

        <EditText
            android:id="@+id/etcompany"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Company"
            android:layout_gravity="center"
            android:inputType="text"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="5dp"
            ></LinearLayout>
        <EditText
            android:id="@+id/etphone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColorHint="#aeb0a5"
            android:hint="Mobile Number"
            android:layout_gravity="center"
            android:inputType="number"
            android:background="#00000000"
            android:textSize="12dp"
            android:letterSpacing="0.1"
            android:layout_marginTop="30dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#c1c1c1"
            android:layout_marginLeft="60dp"
            android:layout_marginRight="60dp"
            android:layout_marginTop="10dp"
            ></LinearLayout>

        <Button
            android:id="@+id/submit"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:scaleType="fitXY"
            android:text="Submit"
            android:layout_gravity="center"
            android:layout_marginTop="22dp"
            android:textSize="12dp"
            android:background="#c1c1c1"


            />


    </LinearLayout>




</RelativeLayout>

Related:

Store data using SQLite by fetching from ContentProvider and display using RecyclerView

Display data in Recyclerview using SQLiteCursor Class in android

SQLite database tutorial

Introduction to SQLite Database

Insert and retrieve data using Android ORMLite database

2. Now Create another file under (java>MainActivity.java). MainActivity.java is the launcher activity.

package com.mytrendin.mydatabase;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText etname,etemail,etcompany,etnumber;
    Button submit;
    String name,email,company,number ;
    RelativeLayout relativeLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
        etname = (EditText) findViewById(R.id.etname);
        etemail = (EditText) findViewById(R.id.etemail);
        etcompany = (EditText) findViewById(R.id.etcompany);
        etnumber = (EditText) findViewById(R.id.etphone);
        submit = (Button) findViewById(R.id.submit);
         name = etname.getText().toString();
         email = etemail.getText().toString();
         company=etcompany.getText().toString();
         number = etnumber.getText().toString();
        relativeLayout = (RelativeLayout) findViewById(R.id.snack);


        submit.setOnClickListener(new  View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Mydatabase mydatabase = new Mydatabase(MainActivity.this);
                boolean trt = mydatabase.insertdata(name,email,company,number);
                if (trt){
                    Snackbar snackbar = Snackbar.make(relativeLayout,"Database Inserted",12000);
                    snackbar.setDuration(12000);
                    snackbar.show();
                    etname.setText("");
                    etemail.setText("");
                    etcompany.setText("");
                    etnumber.setText("");
                }

            }
        });

    }
}

3. Create an another java file(java>Mydatabase.java) name it Mydatabase.java. this class will be responsible for all database operations.

package com.mytrendin.mydatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;

/**
 * Created by csa on 2/27/2017.
 */

public class Mydatabase extends SQLiteOpenHelper {

    private static String DATABASE_NAME = "mynewdatabase";
    private static String TABLE_NAME = "mynewtable";
    private static String ID = "id";
    private static String NAME="name";
    private static String COMPANY="company";
    private static String EMAIL ="email";
    private static String MOBILE="mobile";



    public Mydatabase(Context context) {
        super(context, DATABASE_NAME, null, 1);


    }

    @Override
    public void onCreate(SQLiteDatabase db) {

       String myquery = "CREATE TABLE "+ TABLE_NAME+"("+ID+ " INTEGER AUTO INCREMENT ,"+NAME+" VARCHAR ,"+COMPANY+" VARCHAR , "+EMAIL+ " VARCHAR , "+MOBILE +" INTEGER)";
        db.execSQL(myquery);

    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);

    }

    public boolean insertdata(String name,String email,String company,String number){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(NAME,name);
        contentValues.put(EMAIL,email);
        contentValues.put(COMPANY,company);
        contentValues.put(MOBILE,number);
        long result =db.insert(TABLE_NAME,null,contentValues);

        if (result== -1){
            return false;
        }
        else {

            return true;
        }


    }


}

4. Now open the build.gradle file. to activate the Material design’s feature “Snackbar” add dependencies

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.mytrendin.mydatabase"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.0.1'
    testCompile 'junit:junit:4.12'
}

5. Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytrendin.mydatabase">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

Related Posts