Talk about the Android SQLite database Basesqliteopenhelper

Source: Internet
Author: User

Because the project needs, can not use the file storage, need to use SQLite, originally not how to use, today got nearly a day, and mainly because of a space to delay the time

Below to share the following:

First on code: Basesqliteopenhelper

Package Com.cj.dreams.video.dbhelper;import Android.content.context;import Android.database.DatabaseErrorHandler; Import Android.database.sqlite.sqlitedatabase;import android.database.sqlite.sqliteopenhelper;/** * Created by Fanyafeng on 2015/7/24/0024. */public class Basesqliteopenhelper extends Sqliteopenhelper {public    Basesqliteopenhelper (context context, String Name, Sqlitedatabase.cursorfactory factory, int version) {        Super (context, name, Factory, version);    }    @Override public    void OnCreate (Sqlitedatabase db) {    }    @Override public    void Onupgrade (sqlitedatabase DB, int oldversion, int newversion) {    }}
Bloggers have a habit, is generally can be abstracted into the same writing a base, and then personally feel more convenient

Package Com.cj.dreams.video.dbhelper;import Android.content.context;import Android.database.sqlite.SQLiteDatabase ; Import android.database.sqlite.sqliteopenhelper;/** * Created by Fanyafeng on 2015/7/24/0024. */public class Laughsqliteopenhelper extends Basesqliteopenhelper {private static final String DATABASENAME = "Laughvi    Deo.db ";    private static final int databaseversion = 1;    Three databases private static final String Table_record = "T_record";    private static final String Table_collect = "T_collect";    private static final String Table_good = "T_good";    Public Laughsqliteopenhelper (Context context) {Super (context, DATABASENAME, NULL, databaseversion); } @Override public void OnCreate (Sqlitedatabase db) {String Create_record_sql = "Create TABLE" + Table_reco                RD + "(" + "_id INTEGER PRIMARY KEY," + "v_id VARCHAR () not NULL," + "V_image VARCHAR (255) Not NULL," + "v_Title varchar (255) NOT NULL, "+" V_url VARCHAR (255) is not NULL "+") ";                String create_collect_sql = "Create TABLE" + Table_collect + "(" + "_id INTEGER PRIMARY KEY,"                + "v_id varchar () NOT NULL," + "v_image varchar (255) is not NULL,"        + "V_title varchar (255) NOT NULL," + "v_url varchar (255) is not NULL" + ")";                String create_good_sql = "Create TABLE" + Table_good + "(" + "_id INTEGER PRIMARY KEY,"   + "v_id varchar () not NULL," + "v_ptimes varchar (+)," + "v_ctimes        varchar (+), "+" v_gtimes varchar (50) "+") ";        Db.execsql (Create_record_sql);        Db.execsql (Create_collect_sql);    Db.execsql (Create_good_sql); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {String create_record_sql = "DROP TABLE IF EXISTS" + Table_record;        String create_collect_sql = "DROP TABLE IF EXISTS" + table_collect;        String create_good_sql = "DROP TABLE IF EXISTS" + table_good;        Db.execsql (Create_record_sql);        Db.execsql (Create_collect_sql);        Db.execsql (Create_good_sql);    This.oncreate (DB); }}

Package Com.cj.dreams.video.dbhelper;import Android.database.cursor;import Android.database.sqlite.SQLiteDatabase ; Import Com.cj.dreams.video.util.l;import java.util.arraylist;import java.util.list;/** * Created by Fanyafeng on 2015/ 7/27/0027. */public class Recordtablecourse {    private static final String TABLENAME = "T_record";    Private Sqlitedatabase db = null;    Public Recordtablecourse (Sqlitedatabase db) {        this.db = db;    }    Public Boolean Searchrecord (string v_id) {        string-sql = "Select v_id from" + TABLENAME + "WHERE v_id =?";        String searchfield[] = new string[]{v_id};        Cursor result = This.db.rawQuery (sql, Searchfield);        Result.movetofirst ();        L.D ("Results of the query", Result.getcount ());        if (result.getcount () = = 0) {            return true;        } else {            return false;    }}}
Here to elaborate, because to involve in the insertion, so you need to determine if there is no, then go to insert, and then use Rawquery query if not return is not empty is not O, seemingly 10 address, with ToString fetch return value, then according to this count can get query results

Package Com.cj.dreams.video.dboperate;import Android.content.contentvalues;import android.database.sqlite.sqlitedatabase;/** * Created by Fanyafeng on 2015/7/27/0027.    */public class Collectoperate {private static final String TABLENAME = "T_collect";    Private Sqlitedatabase db = null;    Public collectoperate (Sqlitedatabase db) {this.db = db; }//Insert database public void Insert (String v_id, String v_image, String v_title, String v_ptimes, String v_ctimes, String V        _gtimes, String v_url) {contentvalues contentvalues = new Contentvalues ();        Contentvalues.put ("v_id", v_id);        Contentvalues.put ("V_image", v_image);        Contentvalues.put ("V_title", v_title);        Contentvalues.put ("V_ptimes", v_ptimes);        Contentvalues.put ("V_ctimes", v_ctimes);        Contentvalues.put ("V_gtimes", v_gtimes);        Contentvalues.put ("V_url", V_url);        This.db.insert (TABLENAME, NULL, contentvalues);    This.db.close (); }//Update database public void UpdatE (String v_id, String v_image, String v_title, String v_ptimes, String v_ctimes, String v_gtimes, String v_url) {C        Ontentvalues contentvalues = new Contentvalues ();        Contentvalues.put ("v_id", v_id);        Contentvalues.put ("V_image", v_image);        Contentvalues.put ("V_title", v_title);        Contentvalues.put ("V_ptimes", v_ptimes);        Contentvalues.put ("V_ctimes", v_ctimes);        Contentvalues.put ("V_gtimes", v_gtimes);        Contentvalues.put ("V_url", V_url);        String whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.update (TABLENAME, Contentvalues, Whereclause, Whereargs);    This.db.close ();        }//delete database public void Delete (string v_id) {string whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.delete (TABLENAME, Whereclause, Whereargs);    This.db.close (); }}
Package Com.cj.dreams.video.dboperate;import Android.content.contentvalues;import android.database.sqlite.sqlitedatabase;/** * Created by Fanyafeng on 2015/7/27/0027.    */public class Goodoperate {private static final String TABLENAME = "T_good";    Private Sqlitedatabase db = null;    Public goodoperate (Sqlitedatabase db) {this.db = db; }//Insert database public void Insert (String v_id, String v_ptimes, String v_ctimes, String v_gtimes) {Contentvalues        Contentvalues = new Contentvalues ();        Contentvalues.put ("v_id", v_id);        Contentvalues.put ("V_ptimes", v_ptimes);        Contentvalues.put ("V_ctimes", v_ctimes);        Contentvalues.put ("V_gtimes", v_gtimes);        This.db.insert (TABLENAME, NULL, contentvalues);    This.db.close (); }//Update database public void Update (string v_id, String v_ptimes, String v_ctimes, String v_gtimes) {Contentvalues        Contentvalues = new Contentvalues ();        Contentvalues.put ("v_id", v_id); Contentvalues.puT ("V_ptimes", v_ptimes);        Contentvalues.put ("V_ctimes", v_ctimes);        Contentvalues.put ("V_gtimes", v_gtimes);        String whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.update (TABLENAME, Contentvalues, Whereclause, Whereargs);    This.db.close ();        }//delete database public void Delete (string v_id) {string whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.delete (TABLENAME, Whereclause, Whereargs);    This.db.close (); }}

Package Com.cj.dreams.video.dboperate;import Android.content.contentvalues;import Android.database.sqlite.sqlitedatabase;import com.cj.dreams.video.util.l;/** * Created by Fanyafeng on 2015/7/27/    0027. */public class Recordoperate {private static final String TABLENAME = "T_record";    Private Sqlitedatabase db = null;    Public recordoperate (Sqlitedatabase db) {this.db = db; }//Insert database public void Insert (String v_id, String v_image, String v_title, String v_url) {Contentvalues conte        Ntvalues = new Contentvalues ();        Contentvalues.put ("v_id", v_id);        Contentvalues.put ("V_image", v_image);        Contentvalues.put ("V_title", v_title);        Contentvalues.put ("V_url", V_url);        This.db.insert (TABLENAME, NULL, contentvalues);        L.D ("Database Insert, execute to this");    This.db.close (); }//Update database public void Update (string v_id, String v_image, String v_title, String v_url) {Contentvalues conte        Ntvalues = new Contentvalues (); ContentvalUes.put ("v_id", v_id);        Contentvalues.put ("V_image", v_image);        Contentvalues.put ("V_title", v_title);        Contentvalues.put ("V_url", V_url);        String whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.update (TABLENAME, Contentvalues, Whereclause, Whereargs);    This.db.close ();        }//delete database public void Delete (string v_id) {string whereclause = "v_id=?";        String whereargs[] = new string[]{string.valueof (v_id)};        This.db.delete (TABLENAME, Whereclause, Whereargs);    This.db.close (); }}

For the operation of the database class, the following look at the directory structure first

Take a look at the Operation class

Package Com.cj.dreams.video.fragment;import Android.content.intent;import Android.database.sqlite.sqliteopenhelper;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.view.layoutinflater;import Android.view.view;import Android.view.ViewGroup; Import Android.widget.adapterview;import Android.widget.listview;import Com.cj.dreams.video.r;import Com.cj.dreams.video.activity.videoviewplayingactivity;import Com.cj.dreams.video.adapter.VideoListAdapter; Import Com.cj.dreams.video.bean.videolistbean;import Com.cj.dreams.video.dbhelper.laughsqliteopenhelper;import Com.cj.dreams.video.dbhelper.recordtablecourse;import Com.cj.dreams.video.dboperate.recordoperate;import Com.cj.dreams.video.layout.pulltorefreshlayout;import Com.cj.dreams.video.util.l;import Com.cj.dreams.video.util.postutil;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Java.io.ioexception;import Java.util.arraylist;import java.util.HashMap;import java. util. Linkedhashmap;import Java.util.list;import Java.util.map;public class Rankingfragment extends BaseFragment {private Pu    Lltorefreshlayout Ptrl;    Private ListView ListView;    Private Videolistadapter Videolistadapter;    Private list<videolistbean> videolistbeanlist = new arraylist<videolistbean> ();    Private list<videolistbean> Videolistbeanlist_more = new arraylist<videolistbean> ();    Private list<map<string, object>> videoinfolist = new arraylist<map<string, object>> ();    Private String Id_info, Url_info, Title_info, Image_info;    Operational database public static Laughsqliteopenhelper Laughsqliteopenhelper;    public static recordoperate Recordoperate;    Private Recordtablecourse Recordtablecourse; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {Vi        EW view = inflater.inflate (R.layout.fragment_ranking, container, false);    return view; } @Override public void onactivitycreated (Bundle savedinstancestate) {super.onactivitycreated (savedinstancestate);        This.laughsqliteopenhelper = new Laughsqliteopenhelper (getactivity ());        Laughsqliteopenhelper.getwritabledatabase ();        Initview ();        Thread loadthread = new Thread (new Loadthread ());        Loadthread.start ();    InitData (); private void Initview () {Ptrl = ((pulltorefreshlayout) getactivity (). Findviewbyid (R.id.refresh_ranking_view))        ;        Ptrl.setonrefreshlistener (New MyListener ());        ListView = (ListView) getactivity (). Findviewbyid (R.id.ranking_listview);        Videolistadapter = new Videolistadapter (getactivity (), videolistbeanlist);        Listview.setadapter (Videolistadapter);        Listview.setfocusable (TRUE);    Listview.setonitemclicklistener (New Indexonitemclicklistener ()); } Private class Indexonitemclicklistener implements Adapterview.onitemclicklistener {@Override public vo ID ONITEMCLICK (adapterview<?> Parent, view view, int position, long id) {Intent Intent = new Intent (getactivity (), V            Ideoviewplayingactivity.class); for (int i = 0; I <= position; i++) {if (position = = i) {map map = (map) videoinfol                    Ist.get (i);                    Url_info = (String) map.get ("Url_info");                    Intent.putextra ("Url_info", url_info);                    Id_info = (String) map.get ("Id_info");                    Intent.putextra ("Id_info", id_info);                    Title_info = (String) map.get ("Title_info");                    Intent.putextra ("Title_info", title_info);                    Image_info = (String) map.get ("Image_info");                Intent.putextra ("Image_info", image_info);                }} if (New Recordtablecourse (Laughsqliteopenhelper.getreadabledatabase ()). Searchrecord (Id_info)) { Recordoperate = new Recordoperate (Laughsqliteopenhelper.getreadabLedatabase ());            Recordoperate.insert (Id_info, Image_info, Title_info, Url_info);            Thread postthread = new Thread (new Postthread (Id_info, "play"));            Postthread.start ();        StartActivity (Intent);        }} class Loadthread implements Runnable {@Override public void run () {loaddata (); }} private void LoadData () {try {String backmsg = postutil.postdata (BaseUrl + Gettopvideo, nu            ll);            L.D ("Return parameters obtained from the play Rank", backmsg.tostring ());                try {jsonobject jsonobject = new Jsonobject (backmsg);                Jsonarray Videoarray = Jsonobject.getjsonarray ("video");                Videolistbeanlist_more.clear (); for (int i = 0; i < videoarray.length (); i++) {Videolistbean Videolistbean = new Videolistbean (null                    , NULL, NULL, NULL, NULL, NULL);        Jsonobject object = Videoarray.getjsonobject (i);            Videolistbean.setvideoid (object.getstring ("id"));                    Videolistbean.setvideotitle (object.getstring ("title"));                    Videolistbean.setvideoimage (BaseUrl + object.getstring ("image"));                    Videolistbean.setvideocollecttimes (Integer.parseint (object.getstring ("collect_num") + "");                    Videolistbean.setvideoplaytimes (Integer.parseint (object.getstring ("Play_number") + "");                    Videolistbean.setvideogoodtimes (Integer.parseint (object.getstring ("praise_num") + "");                    Videolistbeanlist.add (Videolistbean);                    map<string, object> idmap = new hashmap<string, object> ();                    Idmap.put ("Url_info", object.getstring ("url"));                    Idmap.put ("Id_info", object.getstring ("id"));                    Idmap.put ("Title_info", Object.getstring ("title"));                    Idmap.put ("Image_info", BaseUrl + object.getstring ("image")); ViDeoinfolist.add (IDMAP);            }} catch (Jsonexception e) {e.printstacktrace ();        }} catch (IOException e) {e.printstacktrace ();        } Message message = Message.obtain ();        Message.what = 0;    Handler.sendmessage (message); } Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {Super.h            Andlemessage (msg);                    Switch (msg.what) {case 0:videolistadapter.update ();            Break    }        }    };        private void InitData () {} class Postthread implements Runnable {private String ID;        Private String type;            Postthread (string ID, String type) {this.id = ID;        This.type = type;        } @Override public void Run () {PostData (id, type);       }} private void PostData (String videoid, String buttontype) { map<string, string> map = new linkedhashmap<> ();        Map.put ("VideoID", videoid);        Map.put ("type", ButtonType);            try {String backmsg = postutil.postdata (BaseUrl + postvideoinfo, map);        L.D ("Run to this, play number plus 1");        } catch (IOException e) {e.printstacktrace (); }} Private class MyListener implements Pulltorefreshlayout.onrefreshlistener {@Override public void                Onrefresh (Final pulltorefreshlayout pulltorefreshlayout) {new Handler () {@Override public void Handlemessage (Message msg) {pulltorefreshlayout.refreshfinish (pulltorefreshlayout.succ                EED);        }}.sendemptymessagedelayed (0, 500);  } @Override public void Onloadmore (final pulltorefreshlayout pulltorefreshlayout) {new Handler () {@Override public void Handlemessage (Message msg) {PulltoRefreshlayout.loadmorefinish (Pulltorefreshlayout.succeed);        }}.sendemptymessagedelayed (0, 500);    }} @Override public void Onresume () {super.onresume ();    } @Override public void OnPause () {super.onpause (); }}
Look at the data structure

Next supplementary details





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Talk about the Android SQLite database Basesqliteopenhelper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.