Sqlite Database Example

R.layout.single_item

Sqlite database is a relational database and has methods to create and delete and execute SQL commands, and common database management tasks

Sqlite helper class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all database management activities.

To use it, 1.Override onCreate(), onUpgrade() methods of SQLiteOpenHelper. Optionally override onOpen() method. 2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.

MainActivity[MainActivity.class]

package com.androidfeeders.sqlcrud;

import android.app.NotificationManager;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Ramasamy on 7/8/2018.
 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = MainActivity.class.getSimpleName();
    PasswordHelper passwordHelper;


    EditText editTextl;
    EditText editText2;
    EditText editTextUserName;

    Button button;
    Button updateButton;
    Button deleteButton;
    Button showButton;

    ImageView imageView;

    TextView resultTextView;
    String URL = "http://i.imgur.com/DvpvklR.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        passwordHelper = new PasswordHelper(this);
        editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        editTextl = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
        imageView = (ImageView) findViewById(R.id.imageView);

        resultTextView = (TextView) findViewById(R.id.result);

        // button initialization
        button = (Button) findViewById(R.id.button);
        updateButton = (Button) findViewById(R.id.update_button);
        deleteButton = (Button) findViewById(R.id.delete_button);
        showButton = (Button) findViewById(R.id.show_button);

        //button  onclick  listener
        button.setOnClickListener(this);
        updateButton.setOnClickListener(this);
        deleteButton.setOnClickListener(this);
        showButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        int id = v.getId();

        switch (id) {

            case R.id.button:
                // Bacckground Task
                new BackgroundTask().execute();


                // Building  notification content and icon
                NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("success")
                        .setContentText("created");


                // notify notification to user
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(0, builder.build());
                break;
            case R.id.update_button:
                String s1 = null;
                String s2 = null;
                s1 = editTextl.getText().toString();
                s2 = editText2.getText().toString();
                if (s1.equals(s2)) {
                    passwordHelper.update("0", editTextUserName.getText().toString(), s1);
                    editTextUserName.setText("");
                    editTextl.setText("");
                    editText2.setText("");
                }

                break;
            case R.id.delete_button:
                passwordHelper.deleteAll();
                break;
            case R.id.show_button:

                Cursor cursor = passwordHelper.getAllData();
                String data= "";
                while (cursor.moveToNext()) {
                    Log.d(TAG, "ShowButton:Click" + cursor.getCount());
                    Log.d(TAG, "ShowButton:Click" + cursor.getString(1) + "\n");
                    data= cursor.getString(1) + "\n";
                }
                resultTextView.setText(data);
                break;
        }
    }

    //  Background Task
    public class BackgroundTask extends AsyncTask {
        String s1 = null;
        String s2 = null;
        String s3 = null;
        Boolean aBoolean;

        @Override
        protected void onPreExecute() {
            s1 = editTextUserName.getText().toString();
            s2 = editTextl.getText().toString();
            s3 = editText2.getText().toString();

        }

        @Override
        protected Void doInBackground(Void... params) {
            if (s2.equals(s3) & !s1.isEmpty()) {
                aBoolean = passwordHelper.insert(s1, s2);
            }
          /*  else if(s1.isEmpty() && s2.isEmpty() && s3.isEmpty()) {
                Toast.makeText(getApplicationContext(),"Please fill All fields",Toast.LENGTH_SHORT).show();
            }*/
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (aBoolean == true) {
                editTextUserName.setText("");
                editTextl.setText("");
                editText2.setText("");
                Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "failure", Toast.LENGTH_LONG).show();
            }
            super.onPostExecute(aVoid);
        }
    }
}

PasswordHelper[PasswordHelper.class]

package com.androidfeeders.sqlcrud;

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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ramasamy on 7/8/2018.
 */

public class PasswordHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "password.db";

    public static final String TABLENAME = "passwordTable";
    public static final String COL1 = "ID";
    public static final String COL2 = "PASSWORD";
    public static final String COL3 = "NAME";


    public PasswordHelper(Context context) {
        super(context, DBNAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLENAME + "( ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,PASSWORD TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE TABLENAME IF EXISTS"+TABLENAME);
    }


    // Method deleting for insert password
    public boolean insert(String name,String password) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, name);
        contentValues.put(COL3, password);
        Long result = sqLiteDatabase.insert(TABLENAME, null, contentValues);
        sqLiteDatabase.close();
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }


    // Method deleting for update password
    public boolean update(String  id,String name,String password) {
            SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(COL2, name);
            contentValues.put(COL3, password);
            sqLiteDatabase.update(TABLENAME,contentValues,"ID=?",new String[]{id});
            sqLiteDatabase.close();
           return  true;
        }


    //Method creation for deleting all password
    public  void deleteAll()
    {
        SQLiteDatabase database = this.getWritableDatabase();
        database.execSQL("delete from "+ TABLENAME);
    }


    // Method Creation for gettting whole password
    public Cursor getAllData()
    {
        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLENAME;
        Cursor cursor= db.rawQuery(selectQuery, null);
        return  cursor;
    }


    // Method deleting for single password
    public void deleteSingle(Integer id)
    {
        SQLiteDatabase db= this.getWritableDatabase();
        String where = COL1+" = '"+id+"'";
        db.delete(TABLENAME, where, null);
    }
    // Method Creation for getting single  password
    public Cursor getRow(String name)
    {
        SQLiteDatabase db= this.getReadableDatabase();
        name= name.replace("'", "''");
        String query = "SELECT * FROM "+TABLENAME+" WHERE "+ COL2+" = '" + name + "'" ;
        Cursor  cursor = db.rawQuery(query,null);
        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

    //Method creation for password count
    public  int getUserCount()
    {
        String countQuery = "SELECT  * FROM " + TABLENAME;
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor=database.rawQuery(countQuery,null);
        cursor.close();
        return cursor.getCount();
    }


}

Layout Resource[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            app:srcCompat="@mipmap/ic_launcher" />

        <EditText
            android:id="@+id/editTextUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:hint="username"
            android:inputType="textPersonName"
            app:layout_editor_absoluteX="60dp"
            app:layout_editor_absoluteY="97dp" />


        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:hint="Password"
            android:inputType="textPersonName"
            app:layout_editor_absoluteX="60dp"
            app:layout_editor_absoluteY="97dp" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:hint="Pasword"
            android:inputType="textPersonName" />

        <LinearLayout
            android:id="@+id/database"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:orientation="horizontal">

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Insert" />

            <Button
                android:id="@+id/update_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="update" />

            <Button
                android:id="@+id/delete_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="delete" />

            <Button
                android:id="@+id/show_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="show" />
        </LinearLayout>

        <TextView
            android:id="@+id/result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:hint="Result" />
    </LinearLayout>
</ScrollView>

Gradle Scripts~build.gradle[Module:app]

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.androidfeeders.sqlcrud"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Gradle Scripts~build.gradle[Project:BaseAdapterSample]

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Resource[strings.xml]

<resources>
    <string name="app_name">sqlcrud</string>
</resources>

manifests

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidfeeders.sqlcrud">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Ramasamy

I started to learn android and Kotlin and iOS and Hybrid application and i cant code IOS very well. But i love more interesting to code and finding new developer minds who are join to me You're welcome to keep on using my website.Instead, you can join our FB page for developer comments and post there: https://www.facebook.com/ramasamy.m.779 Best wishes :) Ramasamy(Software Developer)

Android Development and IOS Development & React Native Application

See what's new in Android & IOS & Hybrid development … explore and learn in site

About Ramasamy

Kotlin and React native example too

Related Posts

3 Comments

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Ramasamy

5 min ago

Kotlin and React native example too

Reply

Leave a reply