Android development-Database Application-SQLite OpenHelper-query and modify a single record

Source: Internet
Author: User
Tags date now

/* (Start of program header annotation)
* Copyright and version Declaration of the program
* Copyright (c) 2011, a student from the computer College of Yantai University
* All rights reserved.
* File name: Database Application-query and modify a single record
* Author: Lei hengxin
* Completion date: January 1, August 14, 2012
* Version No.: V1.0
* Description of tasks and Solutions
* Input description:
* Problem description:
* Program output:
* End the comment in the program Header
*/
 
In the "NotesDbAdapter" class, write the code for "querying a single record" and "modifying". The program is as follows:
[Java]
// Query single entry
Public Cursor get (long rowId) throws SQLException {
Cursor mCursor = db. query (true,
DATABASE_TABLE,
New String [] {KEY_ROWID, KEY_NOTE, KEY_CREATED },
KEY_ROWID + "=" + rowId,
Null, null );
If (mCursor! = Null ){
MCursor. moveToFirst ();
}
Return mCursor;
}
 
// Update
Public boolean update (long rowId, String note ){
ContentValues args = new ContentValues ();
Args. put (KEY_NOTE, note );
 
Return db. update (DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)> 0;
}

 
The complete "NotesDbAdapter. java" program is as follows:
 
[Java]
Package com. demo. android. dummynote;
 
Import java. SQL. Date;
 
Import android. content. ContentValues;
Import android. content. Context;
Import android. database. Cursor;
Import android. database. SQLException;
Import android. database. sqlite. SQLiteDatabase;
Import android. database. sqlite. SQLiteOpenHelper;
Import android. database. sqlite. SQLiteDatabase. CursorFactory;
 
Public class NotesDbAdapter {
Private static final String DATABASE_NAME = "notes. db ";
Private static final int DATABASE_VERSION = 1;
Private static final String DATABASE_TABLE = "notes ";
Private static final String DATABASE_CREATE = "creat table notes ("
+ "_ Id integer primary key," + "note TEXT," + "created INTEGER ,"
+ "Modified INTEGER" + ");";
 
Private static class DatabaseHelper extends SQLiteOpenHelper {
Public DatabaseHelper (Context context ){
Super (context, DATABASE_NAME, null, DATABASE_VERSION );
// TODO Auto-generated constructor stub
}
 
@ Override
Public void onCreate (SQLiteDatabase db ){
// TODO Auto-generated method stub
Db.exe cSQL (DATABASE_CREATE );
 
}
 
@ Override
Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){
// TODO Auto-generated method stub
Db.exe cSQL ("drop table if exists" + DATABASE_TABLE );
OnCreate (db );
}
}
 
Private Context mCtx = null;
Private DatabaseHelper dbHelper;
Private SQLiteDatabase db;
 
Public NotesDbAdapter (Context ctx ){
This. mCtx = ctx;
}
 
Public NotesDbAdapter open () throws SQLException {
DbHelper = new DatabaseHelper (mCtx );
Db = dbHelper. getWritableDatabase ();
Return this;
}
 
Public void close (){
DbHelper. close ();
}
 
Private static final String KEY_ROWID = "_ id ";
Static final String KEY_NOTE = "note ";
Private static final String KEY_CREATED = "created ";

// Get all entries
Public Cursor getall (){
Return db. query (DATABASE_TABLE, // Which table to Select
New String [] {KEY_ROWID, KEY_NOTE, KEY_CREATED}, // Which columns to return
Null, // WHERE clause
Null, // WHERE arguments
Null, // group by clause
Null, // HAVING clause
Null); // Order-by clause
 
}

// Add an entry
Public long create (String Note ){
Date now = new Date ();
ContentValues args = new ContentValues ();
Args. put (KEY_NOTE, Note );
Args. put (KEY_CREATED, now. getTime ());
 
Return db. insert (DATABASE_TABLE, null, args );
}
 
// Remove an entry
Public boolean delete (long rowID ){
Return db. delete (DATABASE_TABLE, KEY_ROWID + "=" + rowID, null)> 0;
}

// Query single entry
Public Cursor get (long rowId) throws SQLException {
Cursor mCursor = db. query (true,
DATABASE_TABLE,
New String [] {KEY_ROWID, KEY_NOTE, KEY_CREATED },
KEY_ROWID + "=" + rowId,
Null, null );
If (mCursor! = Null ){
MCursor. moveToFirst ();
}
Return mCursor;
}
 
// Update
Public boolean update (long rowId, String note ){
ContentValues args = new ContentValues ();
Args. put (KEY_NOTE, note );
 
Return db. update (DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null)> 0;
}
 
 
}
 
Note: The preceding program Date now = new Date (); has a small error. The Compiler prompts the following:
The Date () of the constructor is not defined;
 

 
But there is no parameter in the brackets of Date now = new Date () in the book. If you know what is going on, let me know in the comments.
 
By the way, write the "DummyNote" program:
[Java]
Package com. demo. android. dummynote;
 
Import android. app. ListActivity;
Import android. database. Cursor;
Import android. OS. Bundle;
Import android. view. Menu;
Import android. view. MenuItem;
Import android. widget. ArrayAdapter;
Import android. widget. ListAdapter;
Import android. widget. SimpleCursorAdapter;
Import android. content. Intent;
Import android. widget. ListView;
//////////////////////////////////////// ///////////////
Import android. app. ListActivity;
Import android. content. Intent;
Import android. database. Cursor;
Import android. OS. Bundle;
Import android. util. Log;
Import android. view. ContextMenu;
Import android. view. Menu;
Import android. view. MenuItem;
Import android. view. View;
Import android. view. ContextMenu. ContextMenuInfo;
Import android. widget. AdapterView;
Import android. widget. ListView;
Import android. widget. SimpleCursorAdapter;
 
 
//////////////////////////////////////// /////////////
 
Public class DummyNote extends ListActivity {
/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Tell the list view which view to display when the list is empty
GetListView (). setEmptyView (findViewById (R. id. empty ));
SetAdapter ();
}
Private String [] note_array = {
"Gasolin ",
"Crota ",
"Louk ",
"Magicion"
};
Private NotesDbAdapter mDbHelper;
Private Cursor mNotesCursor;
Private void setAdapter (){
MDbHelper = new NotesDbAdapter (this );
MDbHelper. open ();
FillData ();
}
Private void fillData (){
MNotesCursor = mDbHelper. getall ();
StartManagingCursor (mNotesCursor );

// Create an array to specify the field we want to display in the list
String [] from = new String [] {NotesDbAdapter. KEY_NOTE };

// An array of the fields we want to bind those fields
Int [] to = new int [] {android. R. id. text1 };

// Now create a simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter (this,
Android. R. layout. simple_list_item_1, mNotesCursor, from, );
SetListAdapter (adapter );
}

Private int mNoteNumber = 1;
Protected static final int MENU_INSERT = Menu. FIRST;
Protected static final int MENU_DELETE = Menu. FIRST + 1;
Protected static final int MENU_MODIFY = Menu. FIRST + 1;

@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// TODO Auto-generated method stub
Super. onCreateOptionsMenu (menu );
Menu. add (0, MENU_INSERT, 0, "add notebook ");
Menu. add (0, MENU_DELETE, 0, "delete notebook ");
Return super. onCreateOptionsMenu (menu );
}
 
@ Override
Public boolean onOptionsItemSelected (MenuItem item ){
// TODO Auto-generated method stub
Switch (item. getItemId ()){
Case MENU_INSERT:
String noteName = "Note" + mNoteNumber ++;
MDbHelper. create (noteName );
FillData ();
Return true;
Case MENU_DELETE:
MDbHelper. delete (getListView (). getSelectedItemId ());
FillData ();
Return true;
}
Return super. onOptionsItemSelected (item );
}
 
}
Author: leihengxin

Related Article

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.