Best Code to perform DataBase Operations,in Android

DataBaseOperations.java:-

package org.example.DataBaseOperations;


import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DataBaseOperations extends Activity {
   
    DBAdapter db;
    Button insertBtn,displayBtn,updateBtn,deleteBtn;
    long id;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        db = new DBAdapter(this);
        System.out.println("bool1");
       
        //getting the Id's of the Buttons..
        insertBtn=(Button)findViewById(R.id.button1);
        insertBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                insert();
            }
        });
   

       
        displayBtn=(Button)findViewById(R.id.button2);
         displayBtn.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Perform action on click
                 disAll();
             }
         });
   

        updateBtn=(Button)findViewById(R.id.button3);
        updateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                update();
            }
        });
       
       
        deleteBtn=(Button)findViewById(R.id.button4);
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                del(6);
               
            }
        });
       
       


       
       // insert();
        //disAll();
        //update();//update the table.
        //dis(3);//display 3rd record.
        //del(1);//deletes given Record.
    }
    private void update(){
        db.open();//open() method exists on another class,we call it from here..
        if (db.updateTitle(2,
                "0470285818",
                "C# 2008 Programmer's Reference",
                "Wrox Press"))
            Toast.makeText(this, "Update successful.",
                Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Update failed.",
                Toast.LENGTH_LONG).show();
        //-------------------
        //---retrieve the same title to verify---
        Cursor c = db.getTitle(1);//retrieving the frst row of the 'title' table..
        if (c.moveToFirst())
            DisplayTitle(c);//calling Toast and display the Contents
        else
            Toast.makeText(this, "No title found",
                    Toast.LENGTH_LONG).show();
        //-------------------
        db.close();
    }
    private void insert(){
        db.open();
        //long id;
        id = db.insertTitle(
                "0470285819",
                "Teach yourself Java",
                "Wrox");
        id = db.insertTitle(
                "047017661y",
                "Professional Windows 07 Gadgets Programming",
                "Wrox");
        System.out.println("bool211");
        db.close();
    }
    private void disAll(){
        db.open();
        /*Cursor c = db.getAllTitles();
        if (c.moveToFirst())
        {
            do {
                System.out.println("bool2");
                DisplayTitle(c);
            } while (c.moveToNext());
        }
        else
            System.out.println("boo3l");*/
        try{
            Cursor c = db.getAllTitles();
            if (c.moveToFirst())
            {
                do {
                    System.out.println("bool2");
                    DisplayTitle(c);//calling Toast and display the Contents.
                } while (c.moveToNext());
            }
        }catch(Exception e){
            System.out.println(e);
        }
        db.close();
    }
    private void dis(int j){
        db.open();
        Cursor c = db.getTitle(j);
        if (c.moveToFirst())
            DisplayTitle(c);//calling Toast and display the Contents.
        else
            Toast.makeText(this, "No title found",
                    Toast.LENGTH_LONG).show();
        db.close();
    }       
     private void del(int j){
        db.open();
        if (db.deleteTitle(j))
            Toast.makeText(this, "Delete successful.",
                Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Delete failed.",
                Toast.LENGTH_LONG).show();
        db.close();
    }
    public void DisplayTitle(Cursor c)
    {
        System.out.println("bool");
        Toast.makeText(this,
                "id: " + c.getString(0) + "\n" +
                "ISBN: " + c.getString(1) + "\n" +
                "TITLE: " + c.getString(2) + "\n" +
                "PUBLISHER:  " + c.getString(3),
                Toast.LENGTH_LONG).show();
    }
}

DBAdapter.java:-
    package org.example.DataBaseOperations;
   
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
   
    public class DBAdapter {
        public static final String KEY_ROWID = "_id";
        public static final String KEY_ISBN = "isbn";
        public static final String KEY_TITLE = "title";
        public static final String KEY_PUBLISHER = "publisher";
        private static final String TAG = "DBAdapter";
        private static final String DATABASE_NAME = "books";
        private static final String DATABASE_TABLE = "titles";
        private static final int DATABASE_VERSION = 1;
        private static final String DATABASE_CREATE =
        "create table titles (_id integer primary key autoincrement, "
        + "isbn text not null, title text not null, "
        + "publisher text not null);";
        private final Context context;
        private DatabaseHelper DBHelper;
        private SQLiteDatabase db;
       
    public DBAdapter(Context ctx)
        {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
        }
       
        //creating a 'DatabaseHelper' class...
private static class DatabaseHelper extends SQLiteOpenHelper
        {
        DatabaseHelper(Context context)
        {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);//it invokes a constructor of 'SQLiteOpenHelper'
        }
       
        @Override
    public void onCreate(SQLiteDatabase db)//method of 'SQLiteOpenHelper' and u must be used it.
        {
        db.execSQL(DATABASE_CREATE);
        }
       
        @Override//method of SQLiteOpenHelper,and u must be used it
    public void onUpgrade(SQLiteDatabase db, int oldVersion,
        int newVersion)
        {
        Log.w(TAG, "Upgrading database from version " + oldVersion
        + " to "
        + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS titles");//if DB already Exists,then remove it and create new one.
        onCreate(db);//creating the table with given name..
        }
        }
       
        //---opens the database---it is calling from another Activity..
    public DBAdapter open() throws SQLException
        {
        db = DBHelper.getWritableDatabase();
        return this;
        }
   
        //---closes the database---
    public void close()
        {
        DBHelper.close();
        }
       
        //---insert a title into the database---
    public long insertTitle(String isbn, String title, String publisher)
        {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ISBN, isbn);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_PUBLISHER, publisher);
        return db.insert(DATABASE_TABLE, null, initialValues);
        }
       
        //---deletes a particular title---
    public boolean deleteTitle(long rowId)
        {
        return db.delete(DATABASE_TABLE, KEY_ROWID +
        "=" + rowId, null) > 0;
        }
       
        //---retrieves all the titles---
    public Cursor getAllTitles()
        {
        return db.query(DATABASE_TABLE, new String[] {
        KEY_ROWID,
        KEY_ISBN,
        KEY_TITLE,   //these all r parameters of the string 'new'..
        KEY_PUBLISHER},
        null,null,null,null,null);
        }
       
        //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException
        {
        Cursor mCursor =
        db.query(true, DATABASE_TABLE, new String[] {
        KEY_ROWID,
        KEY_ISBN,
        KEY_TITLE,
        KEY_PUBLISHER
        },
        KEY_ROWID + "=" + rowId,
        null,null,null,null,null);
        if (mCursor != null) {
        mCursor.moveToFirst();
        }
        return mCursor;
        }
       
        //---updates a title---
    public boolean updateTitle(long rowId, String isbn,
        String title, String publisher)
        {
        ContentValues args = new ContentValues();
        args.put(KEY_ISBN, isbn);
        args.put(KEY_TITLE, title);
        args.put(KEY_PUBLISHER, publisher);
        return db.update(DATABASE_TABLE, args,
        KEY_ROWID + "=" + rowId, null) > 0;
        }
        }
   

main.xml:-

<?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    <Button
        android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="insert"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="52dp"></Button>
    <Button
        android:id="@+id/button2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="disAll"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:layout_marginLeft="22dp"></Button>
    <Button
        android:id="@+id/button3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="update"
        android:layout_alignTop="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:layout_marginLeft="29dp"></Button>
    <Button android:id="@+id/button4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Delete"
        android:layout_below="@+id/button2"
        android:layout_alignLeft="@+id/button2"
        android:layout_marginTop="34dp"></Button>
        </RelativeLayout>

Images:
 After pressing the Inser button,press display button.then it displayed all inserted values in DataBase.
It Looks like this:


Comments

Popular posts from this blog

Custom Dialog with no title and full screen in Android

Best working code to set Date limits on Date Picker Dialog,in Android

code to display .pdf,.text,.DOC,.DOCX,.doc extension files exists in SDCard