063 Java Android Program to Read and Write to a SQLite Database in Android
Posted by Superadmin on February 27 2017 04:15:52

Java Android Program to Read and Write to a SQLite Database in Android

Here is source code of the Program to Read and 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.

MainActivity.java

package com.example.databaseread;
 
import java.util.List;
 
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
                // Inserting known Languages
                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");
            }
        });
 
        Button but2 = (Button) findViewById(R.id.Read);
 
        but2.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // Reading data Already present in the Database
                Log.d("Reading: ", "Reading all data..");
                List<values> val = db.getAllvalues();
 
                for (values cn : val) {
                    String log = "Id: " + cn.getId() + " ,values: "
                            + cn.getValue();
                    Log.d("value: ", log);
                }
            }
        });
 
    }
 
    @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.databaseread;
 
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

package com.example.databaseread;
 
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.SQLiteOpenHelper;
 
public class DatabaseHandler extends SQLiteOpenHelper {
 
    private static final int DATABASE_VERSION = 1;
 
    private static final String DATABASE_NAME = "Languages";
 
    // table name
    private static final String TABLE_Languages = "Languages";
 
    // Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
 
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // 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);
    }
 
    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
    }
 
    // Getting single contact
    values getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
 
        Cursor cursor = db.query(TABLE_Languages, new String[] { KEY_ID,
                KEY_NAME }, KEY_ID + "=?", new String[] { String.valueOf(id) },
                null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        values lang = new values(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1));
 
        return lang;
    }
 
    // Getting All data
    public List<values> getAllvalues() {
        List<values> languageList = new ArrayList<values>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_Languages;
 
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
 
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                values lang = new values();
                lang.setId(Integer.parseInt(cursor.getString(0)));
                lang.setValue(cursor.getString(1));
                languageList.add(lang);
            } while (cursor.moveToNext());
        }
 
        return languageList;
    }
 
    // Updating single record
    public int update(values lang) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, lang.getValue());
 
        // updating row
        return db.update(TABLE_Languages, values, KEY_ID + " = ?",
                new String[] { String.valueOf(lang.getId()) });
    }
}

Activity_main.xml

<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/Read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="116dp"
        android:text="READ" />
 
    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/Read"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/Read"
        android:layout_marginTop="72dp"
        android:text="INSERT" />
 
</RelativeLayout>