The background of the story, Jiawu, a large project Tuyu new requirements, the database needs to be transferred from MySQL to SQLite, so the million army vast Nicolas code relocation began, the way after the breakout, finally killed a day, the front came good news, haha ~ ~
This problem troubled for several days, in the StackOverflow search a lot of posts, have not been able to solve, such as:
Getreadabledatabase () Null Pointer exceptionnullpointerexception on Getreadabledatabase () SQLite Android cannot open Database file, and so on.
Finally, the reference to an example, plus my days in SQLite coding experience, finally solved the problem.
1. First is the constructor of the DBHelper class (extends Sqliteopenhelper): Public dbhelper (Context context) {Super (context, database_name, NULL, database_version),//TODO auto-generated Constructor Stub}oncreate () three methods will not elaborate. 2. Write a SQLite operation class
Private DBHelper Dbhelper;private Sqlitedatabase db;//Constructor, it is critical that a DBHelper object is new, initialized Sqlitedatabase//in Android Development Co NText is important, often a bridge between the General class and the Android platform class such as activity. Public Dboperations (Context context) {DBHelper = new DBHelper (context);} The open method of encapsulating SQLite public void open () throws sqlexception{db = Dbhelper.getreadabledatabase ();} Package SQLite Close Method 0public void Close () {dbhelper.close ();}
For example use://Get the user's watch record public list Getviewrecord (user user) {List List = new ArrayList (); String sql = "SELECT * from Showlist where Showid in (select Showid from Viewrecord where userid=?)"; /mydbhelper = new DBHelper (loginactivity.this,dbhelper.database_name,null,dbhelper.database_version);//db = Mydbhelper.getreadabledatabase (); This.open (); cursor cursor = db.rawquery (sql, New String[]{string.valueof (User.getuserid ())}); while (Cursor.movetonext ()) {// String showname = rs.getstring ("ShowName"); List.add (New Show (Cursor.getint (0), cursor.getstring (1), cursor.getstring (2))); LOG.I ("Sql-getviewrecord", Cursor.getint (0) + cursor.getstring (1) + cursor.getstring (2));//System.out.println ("Video name: "+ ShowName);} Cursor.close (); This.close (); return list;}
You can then call this method where you want it.
More information refer to:
Android SQLite Example (recommendation):
http://examples.javacodegeeks.com/android/core/database/sqlite/sqlitedatabase/android-sqlite-example/
Android SQLite Database Tutorial:
http://www.tutorialspoint.com/android/android_sqlite_database.htm
NullPointerException when calling Getreadabledatabase ()