Wednesday, March 20, 2013

How to Create DataBase in Android

In this Post I will discuss about creating your own database and writing  functions for Insertion, Deletion and Updation of Data in Table.


DataBaseHelper:

We will use  SQLiteOpenHelper  class and extend this class
and overside the methods  onCreate, onUpgrade

public class DataBaseHelper extends SQLiteOpenHelper
{
            public DataBaseHelper (Context context, String name,CursorFactory factory, int version)
            {
                       super(context, name, factory, version);
            }
            // Called when no database exists in disk and the helper class needs
            // to create a new one.

            @Override
            public void onCreate(SQLiteDatabase _db)
            {

                     // statement to create the Table
                    _db.execSQL(SMSBlockerDataBaseAdapter.DATABASE_CREATE);
                   
            }
            // Called when there is a database version mismatch meaning that the version
            // of the database on disk needs to be upgraded to the current version.

            @Override
            public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
            {
                    // Log the version upgrade.
                    Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
           
           
                    // Upgrade the existing database to conform to the new version. Multiple
                    // previous versions can be handled by comparing _oldVersion and _newVersion
                    // values.
                    // The simplest case is to drop the old table and create a new one
.
                    _db.execSQL("DROP TABLE IF EXISTS " + "SMSTABLE");
                    // Create a new one.
                    onCreate(_db);
            }
           
}



SMSBlockerDataBaseAdapter


We create a DataBaseAdpater class and write the functions  for following tasks

  • to Open the database
  • to close the database
  • to insert a new Row/Record in Database
  • to delete one or more Records in Database
  • to update the database

In the example Code given below  I have created  a Table to store SMSes with following Columns

Id:   Primary Key of the Table
Sender Name:  Name of SMS Sender
Sender Number:  Phone Number of the Sender
Time:  date and time (In Miliseconds) at which SMS is received

Inserting  a new Record in table


To Insert  a new Record in Table  we need to create an Object of ContentValues  class and put the Values in this  like:

ContentValues newValues = new ContentValues();
                // Assign values for each row.
                newValues.put("COLUMN_NAME1", values);

              newValues.put("COLUMN_NAME2", values);

            and so on
then

// Insert the row into your table
                db.insert("TABLENAME", null, newValues);



Deleting a Record from Table


we can delete a row from the Table with delete method
delete("TABLE ANME",String where, String[]  valuesForWhere)

for Ex:
String where="ID=?";
                int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{ID}) ;


will delete the Record containing IDs in  new String[]{ID}  array.



To get All the Record in the Table


public Cursor getAllEntries ()
        {
             
                return db.query("BLOCKEDSMSTABLE", null,null, null, null, null, "TIME DESC");
        }

TIME DESC    will fetch in descending order of Time , Pass null to fetch in Ascending Order because by Deafault it fetches in ascending Order

To get 1 or more records depending on Some Condition


Task task=new Task();
                Cursor cursor=db.query("BLOCKEDSMSTABLE", null, " ID=?", new String[]{ID}, null, null, null);


"ID=?"       at RunTime ?  will be replaced by string in the Array OF String passed as 4th parameter
the above query will fetch all the records containing the IDs in String Array(4th parameter)


Updating The Table 

Updating is little similar to Inserting  a record in Table
to update the table we need to create an Object of  ContentValues  and put the new Values in ContentValues object

ContentValues updatedValues = new ContentValues();
                // Assign new values for each row.


                updatedValues.put("TIME", taskToBeUpdated.time);
                updatedValues.put("MESSAGE",taskToBeUpdated.message);
                updatedValues.put("RECIPIENTNUMBER",taskToBeUpdated.recipientNumber);
                updatedValues.put("RECIPIENTNAME", taskToBeUpdated.recipientName);
               
               
                String where="ID = ?";
                db.update("SMSTABLE",updatedValues, where, new String[]{ID});


You can Modify the where variable as per your requirement  like where "EMP_ID="  etc.


How to use this DataBaseAdapter Class  in Activities


Create an Instance of  DataBaseAdapter
Open the DataAbse
Call the Functions/Methods

See The Code :


SMSSchedulerDataBaseAdapter  smsSchedulerDataBaseAdapter =new SMSSchedulerDataBaseAdapter(this);
                    smsSchedulerDataBaseAdapter=smsSchedulerDataBaseAdapter.open();

smsSchedulerDataBaseAdapter.insertEntry(yourParameter);
smsSchedulerDataBaseAdapter.getAllEntries();


The Complete Code :


public class SMSBlockerDataBaseAdapter
{
         // Name of the database
        static final String DATABASE_NAME = "SMSBLOCKERDATABASE.db";

        // database version  if creating first time it should be 1      
        static final int DATABASE_VERSION = 1;

        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.
        static final String DATABASE_CREATE = "create table BLOCKEDSMSTABLE " +
                                         "( " +"ID integer primary key autoincrement,MESSAGE text, SENDERNUMBER text, SENDERNAME text, TIME integer ); ";
                                         
        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
       
        public SMSBlockerDataBaseAdapter(Context _context)
        {
                context = _context;
                dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
       
          // Open the Database
        public SMSBlockerDataBaseAdapter open() throws SQLException
        {
                db = dbHelper.getWritableDatabase();
                return this;
        }


         // Close the Database       
        public void close()
        {
                db.close();
        }
   
        public  SQLiteDatabase getDatabaseInstance()
        {
                return db;
        }
   
    // to Insert A record in Table
        public void insertEntry(Task taskToInsert)
        {
                // TODO: Create a new ContentValues to represent the row
                // and insert it into the database.
                ContentValues newValues = new ContentValues();
                // Assign values for each row.
                newValues.put("MESSAGE", taskToInsert.message);
                newValues.put("SENDERNUMBER",taskToInsert.senderNumber);
                newValues.put("SENDERNAME", taskToInsert.senderName);
                newValues.put("TIME",taskToInsert.time);
                               
               
                // Insert the row into your table
                db.insert("BLOCKEDSMSTABLE", null, newValues);
               
       
        }
        public int deleteEntry(String ID)
        {
               
           
                String where="ID=?";
                int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{ID}) ;
              
                return numberOFEntriesDeleted;
               
        }
       
        public void deleteOlderEntries()
        {
                  String olderTime=String.valueOf(new GregorianCalendar().getTimeInMillis()-7*24*60*60*1000);
                  String where="TIME < ?";
                  int numberOFEntriesDeleted= db.delete("BLOCKEDSMSTABLE", where, new String[]{olderTime}) ;
                  Toast.makeText(context, "Number Of Entries Deleted "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        }
        public Cursor getAllEntries ()
        {
              
                return db.query("BLOCKEDSMSTABLE", null,null, null, null, null, "TIME DESC");
        }
       
        public Task getSinlgeEntry(String ID)
        {
               
                Task task=new Task();
                Cursor cursor=db.query("BLOCKEDSMSTABLE", null, " ID=?", new String[]{ID}, null, null, null);
                if(cursor.getCount()==0)
                {
                   
                    return null;
                }
                cursor.moveToFirst();
                task.id= cursor.getString(cursor.getColumnIndex("ID"));
                task.message = cursor.getString(cursor.getColumnIndex("MESSAGE"));
                task.senderNumber = cursor.getString(cursor.getColumnIndex("SENDERNUMBER"));
                task.senderName = cursor.getString(cursor.getColumnIndex("SENDERNAME"));
                task.time = Long.parseLong(cursor.getString(cursor.getColumnIndex("TIME")));
                task.reason=cursor.getString(cursor.getColumnIndex("REASON"));
                //Log.i("getSingle Entry ID: "+"PhoneNumber "+task.senderName+"  "+task.message,ID);
                cursor.close();
                return task;
        }
}




69 comments:

  1. Great article! We will be linking too this great contnt on our site.
    Keep up the good writing.

    ReplyDelete
  2. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    mobile application development training online
    mobile app development course
    mobile application development course
    learn mobile application development
    mobile app development training

    ReplyDelete
  3. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. Techno-based information has been fetched in each of your topics. Sure it will enhance and fill the queries of the public needs. Feeling so glad about your article. Thanks…!
    best software testing training in chennai
    best software testing training institute in chennai with placement
    software testing training
    courses

    software testing training and placement
    software testing training online
    software testing class
    software testing classes in chennai
    best software testing courses in chennai
    automation testing courses in chennai

    ReplyDelete
  4. 7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”

    we have offered to the advanced syllabus course digital marketing for available join now

    more details click the link now

    [url]https://www.webdschool.com/digital-marketing-course-in-chennai.html [/url]

    ReplyDelete
  5. Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, WhatsApp, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now

    more details click the link now

    [url]https://www.webdschool.com/web-development-course-in-chennai.html[/url]

    ReplyDelete
  6. If you plan on whitening your teeth, don't forget that teeth whitening products and procedures whiten only your natural teeth. If you have any implants, veneers, fillings or crowns, their current shade will not be affected by teeth whitening agents.thanks

    ReplyDelete
  7. Learning technological skills seems to be the important thing in this modern era. I thank you for being instructive and kind in this write-up keep it up guys
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  8. I was following your blog regularly and this one is very interesting and knowledge attaining. Great effort ahead. you can also reach us for web development company in chennai website design company in chennai

    ReplyDelete
  9. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    360DigiTMG Data Science Course In Pune
    360DigiTMG Data Science Training In Pune

    Thank you..

    ReplyDelete
  10. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Data Science Course In Hyderabad
    Data Science Training In Hyderabad
    Best Data Science Course In Hyderabad

    Thank you..

    ReplyDelete
  11. I am more curious to take an interest in some of them. I hope you will provide more information on these topics in your next articles.

    Business Analytics Course in Bangalore

    ReplyDelete
  12. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.

    Data Analytics Course in Bangalore

    ReplyDelete
  13. Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
    Data Analyst Course

    ReplyDelete
  14. Thank you so much for this innovative post, keep it up for more valuable information. Visit Ogen Infosystem for professional Website Designing and SEO Services in Delhi, India.
    Web Designing Company in Delhi

    ReplyDelete
  15. Appslure is an award-winning mobile app development company building feature-packed and interactive mobile applications for startups, medium and large enterprises.

    ReplyDelete
  16. I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
    Data Science Training in Chennai

    ReplyDelete
  17. Movie-watching websites that are more than movie-watching websites Because we are the number 1 free movie site in Thailand for a long time, including new movies, Thai movies, Western movies, Asian movies, we have all kinds of ways for you Including new series Full of all stories without interstitial ads to keep annoying anymore. One place sa-movie.com.

    Android and IOS operating systems. Watch online movies, Thai movies, Western movies, Asian movies, Cartoon movies, Netflix Movie, Action Movies, Comedy Movies, Crime Movies, Drama Movies, Horror Movies, Adventure Movies, Crash Movies and still have many new movies to watch. You can watch for free anytime, anywhere 24 hours a day at see4k.com.


    GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, all titles, anywhere, anytime, on mobile, tablet, computer. Android and IOS operating systems. Read top comics, action dramas, comedy, adventure, horror and manga. New coming every day to watch many more. Can be read for free anytime anywhere 24 hours a day at gangmanga.com..

    It is no secret that football is among the most popular and widely watched sports. Everybody who likes football tries to find the best platform for free soccer streaming. So, what are the best free sports streaming sites? We are going to answer this question. On this page, you can find a detailed overview of the most widespread soccer streaming websites. Keep on reading and make the best choice for you live24th.me.

    ReplyDelete
  18. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    cyber security training in bangalore

    ReplyDelete
  19. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging endeavours.
    data science course in bangalore with placement

    ReplyDelete
  20. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    data scientist course in bangalore

    ReplyDelete
  21. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    tableau training in bangalore

    ReplyDelete
  22. I really enjoyed reading your blog. It was very well written and easy to understand. Unlike other blogs that I have read which are actually not very good. Thank you so much!

    Data Science Training in Bangalore

    ReplyDelete
  23. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.

    Artificial Intelligence Training in Bangalore

    ReplyDelete
  24. Are you looking free PPT Submission Sites List?. PDF submission is the method of submitting your web site link in PDF kind including your search phrase.

    ReplyDelete
  25. Impressive blog to be honest definitely this post will inspire many more upcoming aspirants. Eventually, this makes the participants to experience and innovate themselves through knowledge wise by visiting this kind of a blog. Once again excellent job keep inspiring with your cool stuff.

    data science certification in bangalore

    ReplyDelete
  26. Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks
    digital marketing courses in hyderabad with placement

    ReplyDelete
  27. I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.
    Data Science Course Syllabus

    ReplyDelete
  28. This is additionally a generally excellent post which I truly delighted in perusing. It isn't each day that I have the likelihood to see something like this.. data science course in chennai

    ReplyDelete
  29. A good blog always contains new and exciting information and as I read it I felt that this blog really has all of these qualities that make a blog.

    Data Science Training in Bangalore

    ReplyDelete
  30. A good blog always contains new and exciting information, and reading it I feel like this blog really has all of these qualities that make it a blog.

    Artificial Intelligence Training in Bangalore

    ReplyDelete
  31. I am more curious to take an interest in some of them. I hope you will provide more information on these topics in your next articles.

    Machine Learning Course in Bangalore

    ReplyDelete
  32. Some of these criminals can even kidnap your child and demand a ransom. residential securityThere are also rampant cases of armed robberies, carjackings, and terrorist activities. So if you have immense wealth, you need to hire a bodyguard to keep you safe from unwanted life threats.

    ReplyDelete
  33. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    iot training in hyderabad

    ReplyDelete
  34. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
    business analytics courses

    ReplyDelete
  35. I am a new user of this site, so here I saw several articles and posts published on this site, I am more interested in some of them, will provide more information on these topics in future articles.
    data science course in london

    ReplyDelete
  36. I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.

    Artificial Intelligence Course in Bangalore

    ReplyDelete
  37. It's a smart blog. I mean it seriously. You have so much knowledge on this subject and so much passion. He also knows how to get people to join him, obviously from the answers.

    Data Science Course in Nagpur

    ReplyDelete
  38. I have read your article, it is very informative and useful to me, I admire the valuable information you offer in your articles. Thanks for posting it ...

    Business Analytics Course in Patna

    ReplyDelete
  39. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    data science course in varanasi

    ReplyDelete
  40. I'm genuinely getting a charge out of scrutinizing your richly formed articles. Apparently you consume a huge load of energy and time on your blog. I have bookmarked it and I am expecting scrutinizing new articles. Continue to do amazing.data science course in ghaziabad

    ReplyDelete
  41. I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors
    business analytics course in varanasi

    ReplyDelete
  42. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one.
    Continue posting. A debt of gratitude is in order for sharing.
    data analytics course in kolhapur

    ReplyDelete
  43. This is such a great resource that you are providing and you give it away for free.

    Data Analytics Course in Durgapur

    ReplyDelete
  44. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us. data science training in kanpur

    ReplyDelete
  45. Took me time to understand all of the comments, but I seriously enjoyed the write-up. It proved being really helpful to me and Im positive to all of the commenters right here! Its constantly nice when you can not only be informed, but also entertained! I am certain you had enjoyable writing this write-up. data scientist course in surat

    ReplyDelete
  46. I read that Post and got it fine and informative. Please share more like that...
    full stack developer course with placement

    ReplyDelete
  47. Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one.
    Continue posting. A debt of gratitude is in order for sharing.
    business analytics course in warangal

    ReplyDelete
  48. A good blog always comes up with new and exciting information and while reading, I feel that this blog has all those qualities that qualify a blog to be one.
    cyber security course in malaysia

    ReplyDelete
  49. 360DigiTMG, the top-rated organisation among the most prestigious industries around the world, is an educational destination for those looking to pursue their dreams around the globe. The company is changing careers of many people through constant improvement, 360DigiTMG provides an outstanding learning experience and distinguishes itself from the pack. 360DigiTMG is a prominent global presence by offering world-class training. Its main office is in India and subsidiaries across Malaysia, USA, East Asia, Australia, Uk, Netherlands, and the Middle East.

    ReplyDelete
  50. It is perfect chance to make a couple of game plans for the future and the opportunity has arrived to be sprightly. I've scrutinized this post and if I may I have the option to need to suggest you some interesting things or recommendations. Perhaps you could create next articles insinuating this article. I have to examine more things about it! https://360digitmg.com/course/project-management-professional-pmp

    ReplyDelete
  51. Your website is really cool and this is a great inspiring article. data science course in mysore

    ReplyDelete
  52. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    cyber security certification malaysia

    ReplyDelete
  53. Learn to use analytics tools and techniques to manage and analyze large sets of data from Data Science training institutes in Bangalore. Learn to take on business challenges and solve problems by uncovering valuable insights from data. Learn from the comprehensively designed curriculum by the industry experts and work on live projects to sharpen your skills.data science training in hyderabad

    ReplyDelete
  54. You should get certification in the relevant courses if you need to be considered for recruiting data experts.
    data science training in borivali

    ReplyDelete
  55. When you have understood the basic concepts of data science, you must choose a path to move in data science. You need to learn the following courses to be an expert in the field of data science.

    data science course in gorakhpur

    ReplyDelete
  56. I truly adored visiting your post and this content was very unique. Thanks a lot for sharing this...
    Sole custody Virginia
    Protective Order Virginia

    ReplyDelete
  57. Hi,
    Thanks for sharing the information with us it was very informative. Hangup.in

    ReplyDelete
  58. Thank you so much for your excellent blog! I really enjoy to visit your very interesting post, Well done!
    Solicitation Of A Minor VA
    Online Solicitation Of A Minor

    ReplyDelete