Saturday, March 21, 2015

Use database in Android


Lets write a code for the Android application with Login function.
In here Most important thing we need is database.
In android we can use SQlite as our database provider.
Which is integrated in Android OS.

First we need to make a java class Which work as our database handler.
So every time we need to communicate with the database we must call a function in this java class.

When we create the java class   it must extends from SQLiteOpenHelper  Class.
It requires 2 methods to overide an one constructor.

    public DB(Context context) {
        super(context,"SMSDB.db",null,1);
    }

In constructor for super class we need pass 4 arguments.
One is the context
Second is Database name
Third column
Forth column

Methods to overide.
onCreate:- Execute when database create.
onUpgrade:- When SQLite version get update.


Normally Table create query , we write in the onCreate method.
In here I write code for create table which called login.
Columns:-
UserID int PrimaryKey,
createdate datetime default current_timestamp,
Username varchar(10),
Password varchar(255)

What happen when I say create datetime default current_timestamp
When user doesn't provide data while inserting a new row system will automatically inset the Current time when the row record.


How to get data from the database.
So we write anothe method

 public Cursor getAlllogin(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from SMS";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor;
    }

Cursor is the return type:
What is the Cusor?
  Cursor is an object which get the result of the database query.
 I will show how to get the cursor's data in below.



package com.example.nrv.msg;

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


public class MyDB extends SQLiteOpenHelper {
    public DB(Context context) {
        super(context,"SMSDB.db",null,1);
    }

    @Override    public void onCreate(SQLiteDatabase database) {
        String create_login_query = "CREATE TABLE login(UserID int PrimaryKey,create datetime default current_timestamp,Username varchar(10),Password varchar(255))";
        database.execSQL(create_login_query);



    }

    @Override    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {

    }


    public Cursor getAlllogin(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from SMS";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor;
    }

    public void markSms(String id_no){//get the viewd sms ID as string and mark it as viewded        SQLiteDatabase database = this.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put("Viewed", 1);
        database.update("SMS", values, "SmsID" + " = ?", new String[]{id_no});
    }

    public void addSms(String content,String send_by,boolean byme){
        SQLiteDatabase database = this.getReadableDatabase();
        ContentValues values = new ContentValues();
        if (byme){
            values.put("Viewed", 1);
            values.put("Content", content);
            values.put("Smsby", send_by);
            database.insert("SMS",null,values);
        }
        else{
            values.put("Content", content);
            values.put("Smsby", send_by);
            database.insert("SMS",null,values);
        }
    }

    public String getNumber(){
        SQLiteDatabase database = this.getReadableDatabase();
        String selectquery="Select * from maintable";
        Cursor cursor = database.rawQuery(selectquery,null);
        return cursor.getString(cursor.getColumnIndex("SPNumber"));

    }

    public void addNumber(String number){
        if (number.length()==10) {
            if (number.startsWith("0")) {
                number.replaceFirst("0", "+94");
            }
            SQLiteDatabase database = this.getReadableDatabase();
            ContentValues values = new ContentValues();
            values.put("SPNumber", number);
            database.update("maintable", values, "ID" + " = ?", new String[]{"1"});

        }
    }

}




Now You can use this DB interface anywhere in your code as follows.
Example.


package com.example.nrv.msg;

import android.app.ActionBar;
import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {
    MyDB db;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db=new MyDB(this);

        Button x=(Button)findViewById(R.id.button1);
        
        View.OnClickListener p=new View.OnClickListener() {
            @Override            public void onClick(View v) {
                db.addSms("Hello","0123456789",true);
            }
        };
        
        x.setOnClickListener(p);

    }



}


No comments:

Post a Comment