Tuesday, 25 August 2015

Android Programming Tutorials 10 : SQlite Database in Android

SQlite Database:


SQlite DataBase is used to store the data in the table.It is used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database.

SQLite is an Open-Source embedded SQL database engine. This provides relational database management structure for storing user defined records in the form of tables. SQLite is light weight when it comes to resource usage and it doesn’t need to have any server setup like other RDBMS systems. It is an cross platform and self-contained database.

Android SQLite database is an integral part “built-in” component. Any databases you create will be accessible by name to any class in the application, but not outside the application. Here we will see how to use SQLite API to perform database common operations.

                                  



 Create Android Application:
  • File >> New >> Android Application
  • Enter Project name: SQLite App
  • Package: com.ambilpursunil.newapp
  • Keep other default selections, click Next until you reach Finish

  Copy and past the following code in the   MainActivity.java

package com.ambilpursunil.newapp;

import java.sql.SQLException;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SQLiteExample extends Activity implements OnClickListener {
           
                        Button sqlUdate, sqlView, sqlInfo, sqlModify, sqlDelete;
                        EditText sqlName, sqlHotness,sqlRow;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.sqliteexample);
                        sqlUdate = (Button) findViewById(R.id.bSQLUdate);
                        sqlName = (EditText) findViewById(R.id.etSQLName);
                        sqlHotness = (EditText) findViewById(R.id.etSQLHotness);
                        sqlView = (Button) findViewById(R.id.bSQLOpenView);
                        sqlView.setOnClickListener(this);
                        sqlUdate.setOnClickListener(this);
                       
                        sqlRow = (EditText) findViewById(R.id.etSQLrowInfo);
                        sqlInfo = (Button) findViewById(R.id.bgetInfo);
                        sqlModify=(Button) findViewById(R.id.bSQLmodify);
                        sqlDelete =(Button) findViewById(R.id.bSQLdelete);
                        sqlDelete.setOnClickListener(this);
                        sqlModify.setOnClickListener(this);
                        sqlInfo.setOnClickListener(this);
            }
           
            @Override
            public void onClick(View v) {
                        // TODO Auto-generated method stub
                        switch(v.getId()){
                        case R.id.bSQLUdate:
                        boolean didItWork = true;
                        try{
                        String name = sqlName.getText().toString();
                        String hotness = sqlHotness.getText().toString();
                        HotOrNot entry = new HotOrNot(SQLiteExample.this);
                        entry.open();
                        entry.creteEntry(name, hotness);
                        entry.close();
                        }catch (Exception e) {
                        // TODO: handle exceptio
                        didItWork = false;
                        String error = e.toString();
                        Dialog d = new Dialog(this);
                        d.setTitle("SomeThing gone Wrong");
                        TextView tv = new TextView(this);
                        tv.setText(error);
                        d.setContentView(tv);
                        d.show();
                        }
                        finally{
                        if(didItWork){
                        Dialog d = new Dialog(this);
                        d.setTitle("Wel Come To My DB");
                        TextView tv = new TextView(this);
                        tv.Text("Success..!");
                        d.setContentView(tv);
                        d.show();
                        }
                        }
                        break;
                        case R.id.bSQLOpenView:
                        try{
                        Intent i = new Intent("com.stratageeks.newapp.SQLVIEW");
                        startActivity(i);
                        }catch (Exception e) {
                        // TODO: handle exceptio
                        String error = e.toString();
                        Dialog d = new Dialog(this);
                         d.setTitle("SomeThing gone Wrong");
                         TextView tv = new TextView(this);
                         tv.setText(error);
                         d.setContentView(tv);
                         d.show();
                         }
                         break;
                                 
                        case R.id.bgetInfo:
                        try{
                        String s = sqlRow.getText().toString();
                        long l = Long.parseLong(s);
                        HotOrNot hor = new HotOrNot(this);
                        try {
                        hor.open();
                        } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        }
                        String returnedName = hor.getName(l);
                        String retrunedHotness = hor.getHotness(l);
                        hor.close();
                        sqlName.setText(returnedName);
                        sqlHotness.setText(retrunedHotness);
                        }catch (Exception e) {
                        // TODO: handle exceptio
                        String error = e.toString();
                        Dialog d = new Dialog(this);
                        d.setTitle("SomeThing gone Wrong");
                        TextView tv = new TextView(this);
                        tv.setText(error);
                        d.setContentView(tv);
                        d.show();
                        }
                        break;
                        case R.id.bSQLmodify:
                        try{
                        String mName = sqlName.getText().toString();
                        String mHotness = sqlHotness.getText().toString();
                        String sRow = sqlRow.getText().toString();
                        long lRow = Long.parseLong(sRow);
                        HotOrNot hon = new HotOrNot(this);
                        try {
                        hon.open();
                        } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        }
                        hon.updateEntry(lRow, mName, mHotness);
                        hon.close();
                        }catch (Exception e) {
                        // TODO: handle exceptio
                        String error = e.toString();
                        Dialog d = new Dialog(this);
                        d.setTitle("SomeThing gone Wrong");
                        TextView tv = new TextView(this);
                        tv.setText(error);
                        d.setContentView(tv);
                        d.show();
                        }
                        break;
                       case R.id.bSQLdelete:
                       try{
                       String sRow1 = sqlRow.getText().toString();
                       long lRow1 = Long.parseLong(sRow1);
                       HotOrNot hon1 = new HotOrNot(this);
                       hon1.open();
                       hon1.deleteEntry(lRow1);
                       hon1.close();
                       }catch (Exception e) {
                       // TODO: handle exceptio
                      String error = e.toString();
                      Dialog d = new Dialog(this);
                      d.setTitle("SomeThing gone Wrong");
                      TextView tv = new TextView(this);
                      tv.setText(error);
                      d.setContentView(tv);
                      d.show();
                      }
                      break;
                      }
               }
       }

Create  HotOrNOt.java Class and Past the below code;This is user defined class in this class we are definding all the Coloumns of the table and also creating the table, and database with the application

package com.ambilpursunil.newapp;

import java.sql.SQLException;
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 HotOrNot {
                       
                        public static final String KEY_ROWID = "_id";
                        public static final String KEY_NAME = "persons_name";
     public static final String KEY_HOTNESS = "persons_hotness";
                       
    private static final String DATABASE_NAME = "HotOrNotdb";
    private static final String DATABASE_TABLE= "personTable";
                        private static final int DATABASE_VERSION = 1;
                       
                        private DbHelper ourHelper;
                        private Context ourContext;
                        private SQLiteDatabase ourDatabases;
           
                        private static class DbHelper extends SQLiteOpenHelper{

                        public DbHelper(Context context) {
     super(context, DATABASE_NAME, null, DATABASE_VERSION);
                       // TODO Auto-generated constructor stub
                       }

                       @Override
                       public void onCreate(SQLiteDatabase db) {
                       // TODO Auto-generated method stub
                       db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                       KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                       KEY_NAME + " TEXT NOT NULL, " +
                       KEY_HOTNESS + " TEXT NOT NULL);"
                       );
                       }

                       @verride
                       public void onUpgrade(SQLiteDatabase db, int oldVersion,
                       int newVersion) {
                       // TODO Auto-generated method stub
                       db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
                       onCreate(db);
                       }
                       }
                       public HotOrNot(Context c){
                       ourContext = c;
                       }
                       
                       public HotOrNot open() throws SQLException{
                       ourHelper = new DbHelper(ourContext);
                       ourDatabases = ourHelper.getWritableDatabase();
                       return this;
                       }
                       
                       public void close(){
                       ourHelper.close();
                       }

                       public long creteEntry(String name, String hotness)throws SQLException                        {
                       // TODO Auto-generated method stub
                       ContentValues cv = new ContentValues();
                       cv.put(KEY_NAME, name);
                       cv.put(KEY_HOTNESS, hotness);
                       return ourDatabases.insert(DATABASE_TABLE, null, cv);
                       }

                       public String getData() {
                       // TODO Auto-generated method stub
                       String[] columns = new String[]{KEY_ROWID, KEY_NAME,                                          KEY_HOTNESS};
 Cursor c = ourDatabases.query(DATABASE_TABLE, columns, null, null,                                     null, null, null);
                       String result = " ";
                       int iRow = c.getColumnIndex(KEY_ROWID);
                       int iName = c.getColumnIndex(KEY_NAME);
                       int iHotness = c.getColumnIndex(KEY_HOTNESS);
                       for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " +                             c.getString(iHotness) + "\n";
                      }
                      return result;
                      }
                      public String getName(long l)throws SQLException {
                      // TODO Auto-generated method stub
                     String[] columns = new String[]                                                                                  {KEY_ROWID,KEY_NAME,KEY_HOTNESS};
                     Cursor c = ourDatabases.query(DATABASE_TABLE, columns,                                        KEY_ROWID + "=" + l, null, null, null, null);
                     if(c != null){
                     c.moveToFirst();
                     String name =c.getString(1);
                     return name;
                     }
                     return null;
                    }
                     public String getHotness(long l) throws SQLException {
                     // TODO Auto-generated method stub
                     String[] columns = new String[]                                                                                  {KEY_ROWID,KEY_NAME,KEY_HOTNESS};
                     Cursor c = ourDatabases.query(DATABASE_TABLE, columns,                                        KEY_ROWID + "=" + l, null, null, null, null);
                     if(c != null){
                     c.moveToFirst();
                     String hotness =c.getString(2);
                     return hotness;
                     }
                     return null;
                     }
                     public void updateEntry(long lRow, String mName, String                                              mHotness)throws SQLException {
                     // TODO Auto-generated method stub
                     ContentValues vupdate = new ContentValues();
                     vupdate.put(KEY_ROWID, lRow);
                     vupdate.put(KEY_HOTNESS, mHotness);
ourDatabases.update(DATABASE_TABLE, vupdate, KEY_ROWID + "=" +                        lRow, null);
                     }
                     public void deleteEntry(long lRow1)throws SQLException {
                     // TODO Auto-generated method stub
ourDatabases.delete(DATABASE_TABLE, KEY_ROWID + "=" + lRow1,                         null);
                    }
                    }

create a new class in your project src directory and name it as SqlView.java
and Past the below code;This is also a user defined class, in this we are difinding a xml file to show stored data

package com.ambilpursunil.newapp;


import android.app.Activity;

import android.os.Bundle;

import android.view.TextureView;

import android.widget.TextView;



public class SQLView extends Activity {



            @Override

            protected void onCreate(Bundle savedInstanceState) {
                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.sqlview);
                        TextView text = (TextView) findViewById(R.id.tvInfo);
                        HotOrNot info = new HotOrNot(this);
                        try{
                                    info.open();
                        }catch(Exception e){
                                    e.printStackTrace();
                        }
                        String data = info.getData();
                        info.close();
                        text.setText(data);
                        }
                       }
Copy and Past the following xml code by creating another xml file res>>another_main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tablelayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TableRow>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="Names" />

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="Hotness" />
        </TableRow>
    </TableLayout>

    <TextView
        android:id="@+id/tvInfo"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="get info from DB" />

</LinearLayout>

Make the change of  activity_main.xml  file as the below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </ScrollView>

    <EditText
        android:id="@+id/etSQLName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hotness Scale 1 to 10" />

    <EditText
        android:id="@+id/etSQLHotness"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/bSQLUdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update SQLite DB" />

    <Button
        android:id="@+id/bSQLOpenView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Row ID" />

    <EditText
        android:id="@+id/etSQLrowInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/bgetInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Information" />

    <Button
        android:id="@+id/bSQLmodify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit Entry" />

    <Button
        android:id="@+id/bSQLdelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete Entry" />

</LinearLayout>

Copy and past the code for  manifest.xml  file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ambilpursunil.newapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true" 
        android:icon="@drawable/ic_launcher" 
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

    <activity 
       android:name="com.ambilpursunil.newapp.SQLiteExample"
       android:configChanges="keyboard|keyboardHidden|orientation>


   <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />

  </intent-filter>

       </activity>
  </application>
</manifest>

=>Right click on the project and Run As-->Android Application




Enter the data in Edit Text and click on  UpdateSQLiteDB  button then the data will be stored in the database,

If you want to view(See) the stored data just click on the  view button then the data will be appear.

In the below Edit Text of the output screen Enter the row no and click on the  Get Information Button then the data will be appear in the above Edit Text with  Name  and  Hotness Scale 1 to 10.

 EditEntry   EditEntry is used to Edit the Previous data, Just Enter the Row number in the Edit Text i.e..Enter Row ID and click on the EditEntry button and change the data of the both fileds  Name  and  Hotness Scale 1 to 

 DeleteEntry  button is used to delete the data,Just enter the Row number in the Edit Text i.e..Enter Row ID and click on the DeleteEntry Button.

Please Send Your Comments To ambilpura.sunil@gmail.com


Stay Tune For Next Tutorial... Uploading Pictures, Music Files In Android:













































































No comments:

Post a Comment