Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Thread Contributor: Ravishankar ChavareSQLiteDatabse In Android
#1
Android Data Storage Options

1.sharedprefrences
2.Internal storage
3.External storage
4.SQLiteDatabase
5.Network Operations


SQLiteDatabse
SQLite is lighter version of SQL

Today we are learning 
-create SQLiteDatabase
-insert records into Databse
-delete record from Databse
-show all records
-update records


First We need to create database helper class and extends it with SQLiteOpenHelper



Code:
package com.protutr.sqlitedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.Editable;
import android.util.Log;

/**
* Created by ravi on 2/18/2018.
*/

public class DatabaseHelper extends SQLiteOpenHelper {
   private static  final String database_name="contacts.db";
   private  static final int database_version=1;
   private static final String table_name="contact";


   //this is constructor create a SQLiteDatabase instance
   public DatabaseHelper(Context context) {
       super(context, database_name, null, database_version);
       SQLiteDatabase db=this.getWritableDatabase();

   }

   //when DatabaseHelper class Called then first this method will run
   @Override
   public void onCreate(SQLiteDatabase sqLiteDatabase) {
       sqLiteDatabase.execSQL("CREATE TABLE "+table_name+" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,EMAIL TEXT)");
       Log.e("mystring","table created");


   }

   //After second call this method will be called all database update related code will be here
   @Override
   public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
   sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+table_name);
   onCreate(sqLiteDatabase);
   }


   //this method used to insert data into tabele using content value
   public boolean insertData(String name, String mobilenumber, String email) {
       SQLiteDatabase db=this.getWritableDatabase();
       ContentValues contentValues=new ContentValues();
       contentValues.put("NAME",name);
       contentValues.put("MOBILE_NUMBER",mobilenumber);
       contentValues.put("EMAIL",email);
       Log.e("mystring","data inserted");

       long result=db.insert(table_name,null,contentValues);

       if (result==-1)
           return false;


       else
           return true;

   }


   //this method search the data in the datbase
   public Cursor searchData(String mobilenumber){
       SQLiteDatabase db=this.getWritableDatabase();
       String query="SELECT * FROM "+table_name+" WHERE MOBILE_NUMBER= '"+mobilenumber+"' ";
       Cursor cursor=db.rawQuery(query,null);
       return cursor;

   }


   //for delete mobile number
   public void delteData(String mobilenumber){
       SQLiteDatabase db=this.getWritableDatabase();
       db.delete(table_name,"MOBILE_NUMBER= '"+mobilenumber+"'",null);
   }

   //for update data
   public void updateData(String mobilenumber,String name,String email){
       SQLiteDatabase db=this.getWritableDatabase();
       ContentValues contentValues=new ContentValues();
       contentValues.put("EMAIL",email);
       contentValues.put("NAME",name);


       db.update(table_name,contentValues,"MOBILE_NUMBER= '"+mobilenumber+"'",null);
       db.close();
   }


   //to read all data from SQLiteDatabse
   public Cursor AllContacts(){
       SQLiteDatabase db=this.getWritableDatabase();
       Cursor cursor= db.rawQuery("SELECT * FROM "+table_name,null);
       return cursor;

   }
}


In Main Activity Create DatabaseHelper Object Instance

Code:
DatabaseHelper databaseHelper=new DatabaseHelper(this);


when we create above objects it will call to onCreate() method from DatabaseHelper And Create A Table


MainActivity

Code:
package com.protutr.sqlitedemo;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   Button create_db,insertinto_db,search,delete,update,showall,playstore;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       create_db=(Button)findViewById(R.id.createdatabase);
       insertinto_db=(Button)findViewById(R.id.insertintodatbase);
       search=(Button)findViewById(R.id.search);
       delete=(Button)findViewById(R.id.delete);
       update=(Button)findViewById(R.id.update);
       showall=(Button)findViewById(R.id.showall);
       playstore=(Button)findViewById(R.id.playstore);

       playstore.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(Intent.ACTION_VIEW);
               intent.setData(Uri.parse("market://details?id=com.protutr.protutr"));
               startActivity(intent);
           }
       });

       //call activity to show all saved contacts
       showall.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(MainActivity.this,AllContacts.class);
               startActivity(intent);

           }
       });

       //call updatecontact activity to update the contacts
       update.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(MainActivity.this,UpdateContacts.class);
               startActivity(intent);
           }
       });

       //call DeleteContacts activity for deleting contacts
       delete.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(MainActivity.this,DeleteContacts.class);
               startActivity(intent);

           }
       });




   //call to searchindatabase activity to search contacts
       search.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(MainActivity.this,Searchindatabse.class);
               startActivity(intent);

           }
       });

       //this is create databasehelper class instance
       create_db.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(MainActivity.this, "Table created Successfully", Toast.LENGTH_SHORT).show();
               DatabaseHelper databaseHelper=new DatabaseHelper(MainActivity.this);

           }
       });

       //call to insertintodatbase activity
       insertinto_db.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Intent intent=new Intent(MainActivity.this,InsertIntoDatabase.class);
               startActivity(intent);
           }
       });
   }
}


InserIntoDatabase.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.protutr.sqlitedemo.InsertIntoDatabase">

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

       <EditText
           android:id="@+id/name"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="name"/>
       <EditText
           android:id="@+id/mobilenumber"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="Mobile number"/>

       <EditText
           android:id="@+id/email"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="Email"/>

       <Button
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center"
           android:text="Add contacts"
           android:id="@+id/submit"
           />

   </LinearLayout>

</RelativeLayout>

InsertIntoDataBase.java

Code:
package com.protutr.sqlitedemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class InsertIntoDatabase extends AppCompatActivity {
   Button submit;
   EditText name,mobilenumber,email;
   DatabaseHelper databaseHelper;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_insert_into_database);
       submit=(Button)findViewById(R.id.submit);
       name=(EditText)findViewById(R.id.name);
       mobilenumber=(EditText)findViewById(R.id.mobilenumber);
       email=(EditText)findViewById(R.id.email);
       databaseHelper=new DatabaseHelper(this);
       submit.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               boolean result=databaseHelper.insertData(name.getText().toString(),mobilenumber.getText().toString(),email.getText().toString());
               if (result)
                   Toast.makeText(InsertIntoDatabase.this, "Contact Added Successfully", Toast.LENGTH_SHORT).show();
               else
                   Toast.makeText(InsertIntoDatabase.this, "Something went wrong", Toast.LENGTH_SHORT).show();
           }
       });
   }
}

DeleteContacts.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.protutr.sqlitedemo.DeleteContacts">
   <LinearLayout
       android:layout_width="match_parent"
       android:orientation="vertical"
       android:layout_height="wrap_content">
       <EditText
           android:id="@+id/mobilenumber"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="Enter Number"/>
       <Button
           android:id="@+id/delete"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center"
           android:text="Delete"/>
   </LinearLayout>
   <TextView
       android:id="@+id/result"
       android:layout_centerInParent="true"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

</RelativeLayout>

DeleteContacts:

Code:
package com.protutr.sqlitedemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DeleteContacts extends AppCompatActivity {
   EditText mobilenumber;
   Button delete;
   DatabaseHelper databaseHelper;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_delete_contacts);
       mobilenumber=(EditText)findViewById(R.id.mobilenumber);
       delete=(Button)findViewById(R.id.delete);
       databaseHelper=new DatabaseHelper(this);

       delete.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               if(mobilenumber.getText().toString().equals("")){
                   Toast.makeText(DeleteContacts.this, "Enter number", Toast.LENGTH_SHORT).show();
               }
               else {
                   databaseHelper.delteData(mobilenumber.getText().toString());
               }
           }
       });
   }
}

AllContacts.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.protutr.sqlitedemo.AllContacts">
   <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent">
   <TextView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/result"
       />
       </LinearLayout>
   </ScrollView>

</RelativeLayout>

AllContacts

Code:
package com.protutr.sqlitedemo;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AllContacts extends AppCompatActivity {
   DatabaseHelper databaseHelper;
   TextView result;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_all_contacts);
       databaseHelper=new DatabaseHelper(this);
       result=(TextView)findViewById(R.id.result);

       Cursor cursor =databaseHelper.AllContacts();
       if (cursor.getCount()==0){
           Toast.makeText(this, "NO contact found", Toast.LENGTH_SHORT).show();
       }
       else {
           StringBuffer buffer=new StringBuffer();
           while (cursor.moveToNext()){
               Toast.makeText(this, cursor.getString(1), Toast.LENGTH_SHORT).show();
               buffer.append("Id:"+cursor.getString(0)+"\n");
               buffer.append("Name:"+cursor.getString(1)+"\n");
               buffer.append("Mobile:"+cursor.getString(2)+"\n");

               buffer.append("Email:"+cursor.getString(3)+"\n \n");
           }
           result.setText(buffer.toString());


       }


   }
}

SearchInDatabase.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.protutr.sqlitedemo.Searchindatabse">
   <LinearLayout
       android:layout_width="match_parent"
       android:orientation="vertical"
       android:layout_height="wrap_content">
   <EditText
       android:id="@+id/mobilenumber"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Enter Number"/>
   <Button
       android:id="@+id/search"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:text="search"/>
   </LinearLayout>
   <TextView
       android:id="@+id/result"
       android:layout_centerInParent="true"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />

</RelativeLayout>


SearchInDatabase

Code:
package com.protutr.sqlitedemo;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Searchindatabse extends AppCompatActivity {
   EditText mobilenumber;
   Button search;
   TextView result;
   DatabaseHelper databaseHelper;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_searchindatabse);
       mobilenumber=(EditText)findViewById(R.id.mobilenumber);
       search=(Button)findViewById(R.id.search);
       result=(TextView) findViewById(R.id.result);
       databaseHelper=new DatabaseHelper(this);
       search.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Cursor cursor=databaseHelper.searchData(mobilenumber.getText().toString());
               while (cursor.moveToNext()){
                   result.setText(cursor.getString(1));

               }


           }
       });
   }
}



GITHUB PROJECT LINK HERE
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)