Android SQLite Database with Example

Here is source code of the Program to Write to a SQLite Database in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Android Application by uses SQLite Database for handling the Application Specific data in this class teaches you how to create a database and to write to it.Before we go on further let us discuss something about SQLiteOpenHelper.
SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases.
By implementing an SQLiteOpenHelper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened, as well as ensure that each operation is completed efficiently. It’s good practice to defer creating and opening databases until they’re needed. The SQLiteOpenHelper caches database instances after they’ve been successfully opened, so you can make requests to open the database immediately prior to performing a query or a transaction.

MainActivity.java

package com.example.databaseinsert;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final DataBaseHandler db = new DataBaseHandler(this);
        Button but1 = (Button) findViewById(R.id.Insert);
        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.d("Insert: ", "Inserting ..");
                db.add(new Values("value1"));
                db.add(new Values("value2"));
                db.add(new Values("value3"));
                db.add(new Values("value4"));
                Log.d("Insert", "DataBase Successfully Updated");
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Values.java

package com.example.databaseinsert;
 
public class Values {
 
    private long id;
    private String value;
 
    public Values() {
        super();
    }
 
    public Values(String value) {
        super();
        this.value = value;
    }
 
    public Values(long id, String value) {
        super();
        this.id = id;
        this.value = value;
    }
 
    public long getId() {
        return id;
    }
 
    public void setId(long id) {
        this.id = id;
    }
 
    public String getValue() {
        return value;
    }
 
    public void setValue(String value) {
        this.value = value;
    }
}

DataBaseHandler.java

advertisement
advertisement
package com.example.databaseinsert;
 
import java.util.ArrayList;
import java.util.List;
 
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
 
public class DataBaseHandler extends SQLiteOpenHelper {
 
    private static final int DATABASE_VERSION = 1;
 
    private static final String DATABASE_NAME = "Value";
 
    // table name
    private static final String TABLE_Languages = "Values";
 
    // Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "value";
 
    public DataBaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE;
 
        CREATE_CONTACTS_TABLE = "create table " + TABLE_Languages + "("
                + KEY_ID + " integer primary key autoincrement, " + KEY_NAME
                + " text not null);";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_Languages);
        onCreate(db);
    }
 
    public void add(Values lang) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, lang.getValue()); // Contact Name
 
        // Inserting Row
        db.insert(TABLE_Languages, null, values);
        db.close(); // Closing database connection
    }
 
    // Updating single record
    public int update(Values value) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, value.getValue());
 
        // updating row
        return db.update(TABLE_Languages, values, KEY_ID + " = ?",
                new String[] { String.valueOf(value.getId()) });
    }
}

Activity_main.xml

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <Button
        android:id="@+id/Insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="192dp"
        android:text="Insert" />
 
</RelativeLayout>

database_insert

database1

advertisement

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.