Www Tutorialspoint Com Android Android Sqlite Database Htm

Embed Size (px)

Citation preview

  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    1/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Android Basics

    Android - Home

    Android - Overview

    Android - Environment Setup

    Android - Architecture

    Android - Application Components

    Android - Hello World Example

    Android - Resources

    Android - Activities

    Android - Services

    Android - Broadcast Receivers

    Android - Content Providers

    Android - Fragments

    Android - Intents/Filters

    Android - User Interface

    Android - UI Layouts

    Android - UI Controls

    Android - Event Handling

    Android - Styles and Themes

    Android - Custom Components

    Android Advanced Concepts

    Android - Drag and Drop

    Android - Notifications

    http://www.tutorialspoint.com/android/android_user_interface_layouts.htmhttp://www.tutorialspoint.com/android/android_fragments.htmhttp://www.tutorialspoint.com/android/android_services.htmhttp://www.tutorialspoint.com/android/android_resources.htmhttp://www.tutorialspoint.com/android/android_application_components.htmhttp://www.tutorialspoint.com/android/android_environment_setup.htmhttp://www.tutorialspoint.com/android/index.htmhttp://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.tutorialspoint.com/android/index.htmhttp://www.tutorialspoint.com/android/android_overview.htmhttp://www.tutorialspoint.com/android/android_environment_setup.htmhttp://www.tutorialspoint.com/android/android_architecture.htmhttp://www.tutorialspoint.com/android/android_application_components.htmhttp://www.tutorialspoint.com/android/android_hello_world_example.htmhttp://www.tutorialspoint.com/android/android_resources.htmhttp://www.tutorialspoint.com/android/android_acitivities.htmhttp://www.tutorialspoint.com/android/android_services.htmhttp://www.tutorialspoint.com/android/android_broadcast_receivers.htmhttp://www.tutorialspoint.com/android/android_content_providers.htmhttp://www.tutorialspoint.com/android/android_fragments.htmhttp://www.tutorialspoint.com/android/android_intents_filters.htmhttp://www.tutorialspoint.com/android/android_user_interface_layouts.htmhttp://www.tutorialspoint.com/android/android_user_interface_controls.htmhttp://www.tutorialspoint.com/android/android_event_handling.htmhttp://www.tutorialspoint.com/android/android_styles_and_themes.htmhttp://www.tutorialspoint.com/android/android_custom_components.htmhttp://www.tutorialspoint.com/android/android_drag_and_drop.htmhttp://www.tutorialspoint.com/android/android_notifications.htm
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    2/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Location Based Services

    Android - Sending Email

    Android - Sending SMS

    Android - Phone Calls

    Publishing Android Application

    Android Useful Examples

    Android - Alert Dialoges

    Android - Animations

    Android - Audio Capture

    Android - AudioManager

    Android - Auto Complete

    Android - Best Practices

    Android - Bluetooth

    Android - Camera

    Android - Clipboard

    Android - Custom Fonts

    Android - Data Backup

    Android - Developer Tools

    Android - Emulator

    Android - Facebook Integration

    Android - Gestures

    Android - Google Maps

    Android - Image Effects

    Android - ImageSwitcher

    Android - Internal Storage

    Android - JetPlayer

    Android - JSON Parser

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.tutorialspoint.com/android/android_location_based_services.htmhttp://www.tutorialspoint.com/android/android_sending_email.htmhttp://www.tutorialspoint.com/android/android_sending_sms.htmhttp://www.tutorialspoint.com/android/android_phone_calls.htmhttp://www.tutorialspoint.com/android/android_publishing_application.htmhttp://www.tutorialspoint.com/android/android_alert_dialoges.htmhttp://www.tutorialspoint.com/android/android_animations.htmhttp://www.tutorialspoint.com/android/android_audio_capture.htmhttp://www.tutorialspoint.com/android/android_audiomanager.htmhttp://www.tutorialspoint.com/android/android_auto_complete.htmhttp://www.tutorialspoint.com/android/android_best_practices.htmhttp://www.tutorialspoint.com/android/android_bluetooth.htmhttp://www.tutorialspoint.com/android/android_camera.htmhttp://www.tutorialspoint.com/android/android_clipboard.htmhttp://www.tutorialspoint.com/android/android_custom_fonts.htmhttp://www.tutorialspoint.com/android/android_data_backup.htmhttp://www.tutorialspoint.com/android/android_developer_tools.htmhttp://www.tutorialspoint.com/android/android_emulator.htmhttp://www.tutorialspoint.com/android/android_facebook_integration.htmhttp://www.tutorialspoint.com/android/android_gestures.htmhttp://www.tutorialspoint.com/android/android_google_maps.htmhttp://www.tutorialspoint.com/android/android_image_effects.htmhttp://www.tutorialspoint.com/android/android_imageswitcher.htmhttp://www.tutorialspoint.com/android/android_internal_storage.htmhttp://www.tutorialspoint.com/android/android_jetplayer.htmhttp://www.tutorialspoint.com/android/android_json_parser.htmhttp://www.tutorialspoint.com/android/android_json_parser.htm
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    3/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Android - Linkedin Integration

    Android - Loading Spinner

    Android - Localization

    Android - Login Screen

    Android - MediaPlayer

    Android - Multitouch

    Android - Navigation

    Android - Network Connection

    Android - NFC Guide

    Android - PHP/MySQL

    Android - Progress Circle

    Android - ProgressBar

    Android - Push Notification

    Android - RenderScript

    Android - RSS Reader

    Android - Screen Cast

    Android - SDK Manager

    Android - Sensors

    Android - Session Management

    Android - Shared Preferences

    Android - SIP Protocol

    Android - Spelling Checker

    Android - SQLite Database

    Android - Support Library

    Android - Testing

    Android - Text to Speech

    Android - TextureView

    http://www.tutorialspoint.com/android/android_json_parser.htmhttp://www.tutorialspoint.com/android/android_json_parser.htmhttp://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.tutorialspoint.com/android/android_json_parser.htmhttp://www.tutorialspoint.com/android/android_linkedin_integration.htmhttp://www.tutorialspoint.com/android/android_loading_spinner.htmhttp://www.tutorialspoint.com/android/android_localization.htmhttp://www.tutorialspoint.com/android/android_login_screen.htmhttp://www.tutorialspoint.com/android/android_mediaplayer.htmhttp://www.tutorialspoint.com/android/android_multitouch.htmhttp://www.tutorialspoint.com/android/android_navigation.htmhttp://www.tutorialspoint.com/android/android_network_connection.htmhttp://www.tutorialspoint.com/android/android_nfc_guide.htmhttp://www.tutorialspoint.com/android/android_php_mysql.htmhttp://www.tutorialspoint.com/android/android_progress_circle.htmhttp://www.tutorialspoint.com/android/android_progressbar.htmhttp://www.tutorialspoint.com/android/android_push_notification.htmhttp://www.tutorialspoint.com/android/android_renderscript.htmhttp://www.tutorialspoint.com/android/android_rss_reader.htmhttp://www.tutorialspoint.com/android/android_screen_cast.htmhttp://www.tutorialspoint.com/android/android_sdk_manager.htmhttp://www.tutorialspoint.com/android/android_sensors.htmhttp://www.tutorialspoint.com/android/android_session_management.htmhttp://www.tutorialspoint.com/android/android_shared_preferences.htmhttp://www.tutorialspoint.com/android/android_sip_protocol.htmhttp://www.tutorialspoint.com/android/android_spelling_checker.htmhttp://www.tutorialspoint.com/android/android_sqlite_database.htmhttp://www.tutorialspoint.com/android/android_support_library.htmhttp://www.tutorialspoint.com/android/android_testing.htmhttp://www.tutorialspoint.com/android/android_text_to_speech.htmhttp://www.tutorialspoint.com/android/android_textureview.htm
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    4/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Android - Twitter Integration

    Android - UI Deign

    Android - UI Patterns

    Android - UI Testing

    Android - WebView Layout

    Android - Wi-Fi

    Android - Widgets

    Android - XML Parsers

    Pascal Useful Resources

    Android - Useful Resources

    Android - Discussion

    Previous Page Next Page

    Android - SQLite Database Tutorial

    Advertisements

    SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.

    SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

    The main package is android.database.sqlite that contains the classes to manage your own databases

    In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive

    in your own object.Its syntax is given below

    SQLiteDatabse mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);

    Apart from this , there are other functions available in the database package , that does this job. They are listed below

    Sr.No Method & Description

    1 openDatabase (String path, SQLiteDatabase.Cursor Factory factory, int flags, DatabaseError Handler err orHandler )

    This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY

    Database - Package

    Database - Creation

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.tutorialspoint.com/android/android_twitter_integration.htmhttp://www.tutorialspoint.com/android/android_ui_deign.htmhttp://www.tutorialspoint.com/android/android_ui_patterns.htmhttp://www.tutorialspoint.com/android/android_ui_testing.htmhttp://www.tutorialspoint.com/android/android_webview_layout.htmhttp://www.tutorialspoint.com/android/android_wi_fi.htmhttp://www.tutorialspoint.com/android/android_widgets.htmhttp://www.tutorialspoint.com/android/android_xml_parsers.htmhttp://www.tutorialspoint.com/android/android_useful_resources.htmhttp://www.tutorialspoint.com/android/android_discussion.htmhttp://www.tutorialspoint.com/android/android_spelling_checker.htmhttp://www.tutorialspoint.com/android/android_support_library.htmhttps://googleads.g.doubleclick.net/aclk?sa=l&ai=CJMM685-0VYHxBciSMISsrfgJjNL45wfE7YOrjwGR_ILjCRABIIW12wVgyYb-i8yk1BmgAYTBmdsDyAECqQIAYAfCO8BQPqgDAcgDwQSqBKgBT9A-QTL-Fc4ggPO4moPrq2WcFe6u2vfKxKeWXXb7CL00rksPDMDMrcDrUIVLL-J_JPOc-05ZILU8iYPrnK8_kF2ik2nAuFlS49m7EbwaoGRaEbzxVtVRQ-VQxgv-tvAx4okayPYL9GjeODce3gOHlml1b_B83jruXMawhi9AGNLdvTblGRFDZCqSgrux2EmuJByEAh1JefhhRCu5A0FS_gbr0APeuy5-oAYCgAfkvuYkqAemvhvYBwE&num=1&sig=AOD64_2n9QX4M_G6TeeyFPvaeAYMyGMo0g&client=ca-pub-7133395778201029&adurl=http://www.dezyre.com/Big-Data-and-Hadoop/19
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    5/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    2 openDatabase (String path, SQLiteDatabase.Cursor Factory factory, int flags)

    It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases

    3 openOrCr eateDatabase (String path, SQLiteDatabase.CursorF actory factory)

    It not only opens but create the database if it not exists. This method is equivalent to openDatabase method

    4 openOrCr eateDatabase (File file, SQLiteDatabase.CursorF actory factory)

    This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to f ile.getPath()

    we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below

    mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);");

    mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

    This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below

    Sr.No Method & Description

    1 execSQL(String sql, Object[] bindArgs)

    This method not only insert data , but also used to update or modify already existing data in database using bind arguments

    We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the

    cursor forward and retrieve the data.

    Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);

    resultSet.moveToFirst();

    String username = resultSet.getString(1);

    String password = resultSet.getString(2);

    There are other functions available in the Cursor class that allows us to effectively retrieve the dat a. That includes

    Sr .No Me th od & De sc ript io n

    1 getColumnCount()This method return the total number of columns of the table.

    2 getColumnInde x(String columnName)

    This method returns t he index number of a column by specifying the name of the column

    3 getColumnName(int columnIndex)

    This method returns the name of the column by specifying the index of the column

    4 getColumnNames()

    This method returns the arr ay of all the column names of the table.

    5 getCount()

    This method returns the total number of rows in the cursor

    Database - Insertion

    Database - Fetching

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    6/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    6 getPosition()

    This method returns the current position of the cursor in the table

    7 isClosed()

    This method returns true if the cursor is closed and retur n false otherwise

    For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its syntax is given

    below

    public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(){

    super(context,DATABASE_NAME,null,1);

    }

    public void onCreate(SQLiteDatabase db) {}

    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}

    }

    Here is an example demonstrating the use of SQLite Database. It creates a basic contacts applications that allows insertion , deletion and modification of contacts.

    To experiment with this example , you need to run this on an actual device on which camera is supported.

    s

    Steps Description

    1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. While creating this project, make sure you Target SDK and Compile With at

    the latest version of Android SDK to use higher levels of APIs.

    2 Modify src/MainActivity.java file to get references of all the XML components and populate the contacts on listView.

    3 Create new src/DBHelper.java that will manage the database work

    4 Create a new Activity as DisplayContact.java that will display the contact on the screen

    5 Modify the res/layout/activity_main to add respective XML components

    6 Modify the res/layout/activity_display_contact.xml to add respective XML components

    7 Modify the res/values/string.xml to add necessary string components

    8 Modify the res/menu/display_contact.xml to add necessary menu components

    9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

    10 Run the application and choose a running android device and install the application on it and verify the results.

    Following is the content of the modified MainActivity.java .

    package com.example.sairamkrishna.myapplication;

    import android.content.Context;

    import android.content.Intent;

    import android.support.v7.app.ActionBarActivity;

    import android.os.Bundle;

    import android.view.KeyEvent;

    Database - Helper class

    Example

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    7/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    import android.view.Menu;

    import android.view.MenuItem;

    import android.view.View;

    import android.widget.AdapterView;

    import android.widget.ArrayAdapter;

    import android.widget.AdapterView.OnItemClickListener;

    import android.widget.ListView;

    import java.util.ArrayList;

    import java.util.List;

    public class MainActivity extends ActionBarActivity {

    public final static String EXTRA_MESSAGE = "MESSAGE";

    private ListView obj;

    DBHelper mydb;

    @Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mydb = new DBHelper(this);

    ArrayList array_list = mydb.getAllCotacts();

    ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

    obj = (ListView)findViewById(R.id.listView1);

    obj.setAdapter(arrayAdapter);

    obj.setOnItemClickListener(new OnItemClickListener(){

    @Override

    public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3) {

    // TODO Auto-generated method stub

    int id_To_Search = arg2 + 1;

    Bundle dataBundle = new Bundle();

    dataBundle.putInt("id", id_To_Search);

    Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

    intent.putExtras(dataBundle);

    startActivity(intent);

    }

    });

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;

    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item){

    super.onOptionsItemSelected(item);

    switch(item.getItemId())

    {

    case R.id.item1:Bundle dataBundle = new Bundle();

    dataBundle.putInt("id", 0);

    Intent intent = new Intent(getApplicationContext(),DisplayContact.class);

    intent.putExtras(dataBundle);

    startActivity(intent);

    return true;

    default:

    return super.onOptionsItemSelected(item);

    }

    }

    public boolean onKeyDown(int keycode, KeyEvent event) {

    if (keycode == KeyEvent.KEYCODE_BACK) {

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    8/20

    pdfcrowd comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    moveTaskToBack(true);

    }

    return super.onKeyDown(keycode, event);

    }

    }

    Following is the modified content of display contact activity DisplayContact.java

    package com.example.addressbook;

    import android.os.Bundle;

    import android.app.Activity;

    import android.app.AlertDialog;

    import android.content.DialogInterface;

    import android.content.Intent;

    import android.database.Cursor;

    import android.view.Menu;

    import android.view.MenuItem;

    import android.view.View;

    import android.widget.Button;

    import android.widget.TextView;

    import android.widget.Toast;

    public class DisplayContact extends Activity {

    int from_Where_I_Am_Coming = 0;

    private DBHelper mydb ;

    TextView name ;

    TextView phone;

    TextView email;

    TextView street;

    TextView place;

    int id_To_Update = 0;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_display_contact);

    name = (TextView) findViewById(R.id.editTextName);

    phone = (TextView) findViewById(R.id.editTextPhone);

    email = (TextView) findViewById(R.id.editTextStreet);

    street = (TextView) findViewById(R.id.editTextEmail);

    place = (TextView) findViewById(R.id.editTextCity);

    mydb = new DBHelper(this);

    Bundle extras = getIntent().getExtras();

    if(extras !=null)

    {

    int Value = extras.getInt("id");

    if(Value>0){ //means this is the view part not the add contact part.

    Cursor rs = mydb.getData(Value);

    id_To_Update = Value;

    rs.moveToFirst();

    String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));

    String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));

    String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));

    String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));

    String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));

    if (!rs.isClosed())

    {

    rs.close();

    }

    Button b = (Button)findViewById(R.id.button1);

    b.setVisibility(View.INVISIBLE);

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    9/20

    df d mi b PRO i Are you a developer? Try out the HTML to PDF API

    name.setText((CharSequence)nam);

    name.setFocusable(false);

    name.setClickable(false);

    phone.setText((CharSequence)phon);

    phone.setFocusable(false);

    phone.setClickable(false);

    email.setText((CharSequence)emai);

    email.setFocusable(false);

    email.setClickable(false);

    street.setText((CharSequence)stree);

    street.setFocusable(false);

    street.setClickable(false);

    place.setText((CharSequence)plac); place.setFocusable(false);

    place.setClickable(false);

    }

    }

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    Bundle extras = getIntent().getExtras();

    if(extras !=null)

    {

    int Value = extras.getInt("id");

    if(Value>0){

    getMenuInflater().inflate(R.menu.display_contact, menu);

    }

    else{ getMenuInflater().inflate(R.menu.main, menu);

    }

    }

    return true;

    }

    public boolean onOptionsItemSelected(MenuItem item)

    {

    super.onOptionsItemSelected(item);

    switch(item.getItemId())

    {

    case R.id.Edit_Contact:

    Button b = (Button)findViewById(R.id.button1);

    b.setVisibility(View.VISIBLE);

    name.setEnabled(true);

    name.setFocusableInTouchMode(true);

    name.setClickable(true);

    phone.setEnabled(true); phone.setFocusableInTouchMode(true);

    phone.setClickable(true);

    email.setEnabled(true);

    email.setFocusableInTouchMode(true);

    email.setClickable(true);

    street.setEnabled(true);

    street.setFocusableInTouchMode(true);

    street.setClickable(true);

    place.setEnabled(true);

    place.setFocusableInTouchMode(true);

    place.setClickable(true);

    return true;

    case R.id.Delete_Contact:

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    10/20

    df di b PRO i Are you a developer? Try out the HTML to PDF API

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setMessage(R.string.deleteContact)

    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int id) {

    mydb.deleteContact(id_To_Update);

    Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);

    startActivity(intent);

    }

    })

    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int id) {

    // User cancelled the dialog

    }

    });

    AlertDialog d = builder.create();

    d.setTitle("Are you sure"); d.show();

    return true;

    default:

    return super.onOptionsItemSelected(item);

    }

    }

    public void run(View view)

    {

    Bundle extras = getIntent().getExtras();

    if(extras !=null)

    {

    int Value = extras.getInt("id");

    if(Value>0){

    if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){

    Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();

    Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent);

    }

    else{

    Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();

    }

    }

    else{

    if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){

    Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();

    }

    else{

    Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();

    }

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);

    startActivity(intent);

    }

    }

    }}

    Following is the content of Database class DBHelper.java

    package com.example.addressbook;

    import java.util.ArrayList;

    import java.util.HashMap;

    import java.util.Hashtable;

    import android.content.ContentValues;

    import android.content.Context;

    import android.database.Cursor;

    import android.database.DatabaseUtils;

    import android.database.sqlite.SQLiteOpenHelper;

    import android.database.sqlite.SQLiteDatabase;

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    11/20

    df di b PRO i A d l ? T t th HTML t PDF API

    public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";

    public static final String CONTACTS_TABLE_NAME = "contacts";

    public static final String CONTACTS_COLUMN_ID = "id";

    public static final String CONTACTS_COLUMN_NAME = "name";

    public static final String CONTACTS_COLUMN_EMAIL = "email";

    public static final String CONTACTS_COLUMN_STREET = "street";

    public static final String CONTACTS_COLUMN_CITY = "place";

    public static final String CONTACTS_COLUMN_PHONE = "phone";

    private HashMap hp;

    public DBHelper(Context context)

    {

    super(context, DATABASE_NAME , null, 1);

    }

    @Override public void onCreate(SQLiteDatabase db) {

    // TODO Auto-generated method stub

    db.execSQL(

    "create table contacts " +

    "(id integer primary key, name text,phone text,email text, street text,place text)"

    );

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS contacts");

    onCreate(db);

    }

    public boolean insertContact (String name, String phone, String email, String street,String place)

    {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues(); contentValues.put("name", name);

    contentValues.put("phone", phone);

    contentValues.put("email", email);

    contentValues.put("street", street);

    contentValues.put("place", place);

    db.insert("contacts", null, contentValues);

    return true;

    }

    public Cursor getData(int id){

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );

    return res;

    }

    public int numberOfRows(){

    SQLiteDatabase db = this.getReadableDatabase();

    int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);

    return numRows; }

    public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)

    {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();

    contentValues.put("name", name);

    contentValues.put("phone", phone);

    contentValues.put("email", email);

    contentValues.put("street", street);

    contentValues.put("place", place);

    db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );

    return true;

    }

    public Integer deleteContact (Integer id)

    {

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    12/20df di b PRO i A d l ? T t th HTML t PDF API

    SQLiteDatabase db = this.getWritableDatabase();

    return db.delete("contacts",

    "id = ? ",

    new String[] { Integer.toString(id) });

    }

    public ArrayList getAllCotacts()

    {

    ArrayList array_list = new ArrayList();

    //hp = new HashMap();

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor res = db.rawQuery( "select * from contacts", null );

    res.moveToFirst();

    while(res.isAfterLast() == false){

    array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));

    res.moveToNext(); }

    return array_list;

    }

    }

    Following is the content of the res/layout/activity_main.xml

  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    13/20df di b PRO i

    Are you a developer? Try out the HTML to PDF API

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerHorizontal="true"

    android:layout_centerVertical="true" >

    ;

    Following is the content of the res/layout/activity_display_contact.xml

  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    14/20df di b PRO iAre you a developer? Try out the HTML to PDF API

    android:text @string/email

    android:textAppearance="?android:attr/textAppearanceMedium" />

    Following is the content of the res/value/string.xml

    Address Book

    Settings

    Hello world!

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    15/20df di b PRO iAre you a developer? Try out the HTML to PDF API

    g _ g

    Add New

    Edit Contact

    Delete Contact

    DisplayContact

    Name

    Phone

    Email

    Street

    City/State/Zip

    Save Contact

    Are you sure, you want to delete it.

    Yes

    No

    Following is the content of the res/menu/main_menu.xml

    Following is the content of the res/menu/display_contact.xml

    This is the defualt AndroidManifest.xml of this project

    Let's tr y to run your application I assume you have connected your actual Android Mobile device with your computer To run the app fr om Android studio open one of your project's activity files and click Run

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    16/20

    Are you a developer? Try out the HTML to PDF API

    Let s tr y to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app fr om Android studio , open one of your project s activity files and click Run

    icon from the t ool bar. Before starting your application,Android studio will display following window to select an option where you want to run your Android application.

    Select your mobile device as an opt ion and then check your mobile device which will display following screen

    Now open your optional menu, it will show as below image:Optional menu appears different places on different versions

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    17/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Click on the add button of the menu screen to add a new contact. It will display the following screen

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    18/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    It will display the following fields. Please enter the required information and click on save contact. It will bring you back to main screen.

    Now our contact john has been added. T ap on this to edit it or delete it.It will bring you to the following screen. Now select menu from your mobile. And there will be two options there.

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    19/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Select delete contact and an dialog box would appear asking you about deleting this contact. It would be like this

    Select Yes from the above screen that appears and a notification will appear that the contact has been deleted successfully. It would appear like this

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdf
  • 7/23/2019 Www Tutorialspoint Com Android Android Sqlite Database Htm

    20/20

    pdfcrowd.comopen in browser PRO version Are you a developer? Try out the HTML to PDF API

    Previous Page Next Page

    In order to see that where is your database is created. Open your android studio, connect your mobile. Go tools/android/android device monitor. Now browse the file explorer tab. Now browse this folder

    /data/data//databases.

    Advertisements

    Copyright 2015. All Rights Reserved.

    About us Write for us Contact

    http://pdfcrowd.com/http://pdfcrowd.com/redirect/?url=http%3a%2f%2fwww.tutorialspoint.com%2fandroid%2fandroid_sqlite_database.htm&id=ma-150726045309-7e54f1a6http://pdfcrowd.com/customize/http://pdfcrowd.com/html-to-pdf-api/?ref=pdfhttp://www.tutorialspoint.com/android/android_spelling_checker.htmhttp://www.tutorialspoint.com/android/android_support_library.htmhttps://googleads.g.doubleclick.net/aclk?sa=l&ai=CTdBw85-0VaqnCpCAMYzzm-gMk9Xm0AaztajQjAKjlfT9CBABIIW12wVgyYb-i8yk1BmgAa3Rx9YDyAECqAMByAPBBKoErgFP0K8XKKhnEKF7r5Yl2JRUbMYRSPES4f4F6sfTBBz5pZBuVHg5IDFjWbX2eghxnTPWeqyHQirn_yW5ib-am-M59P1FFBRKQ2gIwqmT0t3qBqGmdZ8O2RgHIDTTru4OM1Q4zjBEsFvDGB2qs2bOWCT0LA2A7j3VjH__qOgs7fcZr8FxuZF9t5fOHbyjZ1zeh7h4RR3HcBJstEpi7Ab8ddkFh9JKhZEV0hvgT2V1J_GgBgKAB7uuuCmoB6a-G9gHAQ&num=1&sig=AOD64_1X_2mLg38DbOLpHr3gnrrxQfW_Fg&client=ca-pub-7133395778201029&adurl=http://pixel.everesttech.net/4469/cq%3Fev_sid%3D3%26ev_ln%3D%26ev_lx%3D%26ev_crx%3D72120972403%26ev_mt%3D%26ev_n%3Dd%26ev_ltx%3D%26ev_pl%3Dwww.tutorialspoint.com%26ev_pos%3Dnone%26ev_dvc%3Dc%26ev_dvm%3D%26ev_phy%3D1024543%26ev_loc%3D%26ev_cx%3D294549043%26ev_ax%3D19788299443%26url%3Dhttps://developer.amazon.com/public/solutions/alexa/alexa-skills-kit%253Fsc_channel%253DDisplay%2526sc_country%253DUS%2526sc_publisher%253DGoogle-GDN%2526sc_category%253DDigital-Launch%2526sc_content%253DAlexaEcho-Launch%2526sc_campaign%253DUS-AlexaEchoLaunch%2526sc_brand%253DAlexa%2526sc_detail%253DAlexaEchoTeach%2526sc_place%253D300x250%2526sc_itrackingcode%253DSEM0050%2526sc_medium%253DDisplay_US_Google-GDN_Digital-Launch_AlexaEcho-Launch_US-AlexaEchoLaunch_Alexa_AlexaEchoTeach_300x250_SEM0050%2526s_kwcid%253DAL!4469!3!72120972403!!www.tutorialspoint.com!d!!http://www.tutorialspoint.com/index.htmhttp://www.tutorialspoint.com/about/index.htmhttp://www.tutorialspoint.com/about/tutorials_writing.htmhttp://www.tutorialspoint.com/about/contact_us.htm