原文:https://developer.android.com/training/basics/data-storage/databases.html
- Define a Schema and Contract
|
|
- FeedEntryDb
|
|
- Create a Database Using a SQL Helper
|
|
DatabaseManger,包括增删改查
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142package com.xiaomolong.sqlitesample;import java.util.ArrayList;import java.util.List;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import com.xiaomolong.sqlitesample.FeedReaderContract.FeedEntry;public class DatabaseManger {private static FeedReaderDbHelper mFeedReaderDbHelper = null;DatabaseManger(Context context) {getInstance(context);}public static void getInstance(Context context) {if (mFeedReaderDbHelper == null) {mFeedReaderDbHelper = new FeedReaderDbHelper(context);}}/*** 插入** @return the row ID of the newly inserted row, or -1 if an error occurred*/public long insert(FeedEntryDb feedEntry) {// Gets the data repository in write modeSQLiteDatabase db = mFeedReaderDbHelper.getWritableDatabase();// Create a new map of values, where column names are the keysContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, feedEntry.getEntryid());values.put(FeedEntry.COLUMN_NAME_TITLE, feedEntry.getTitle());values.put(FeedEntry.COLUMN_NAME_SUBTITLE, feedEntry.getSubtitle());// Insert the new row, returning the primary key value of the new rowlong newRowId;newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);db.close();return newRowId;}/*** 查询或通过条件查询** @param rowId* @return*/public List<FeedEntryDb> query(int rowId) {SQLiteDatabase db = mFeedReaderDbHelper.getReadableDatabase();// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection = { FeedEntry._ID, FeedEntry.COLUMN_NAME_ENTRY_ID,FeedEntry.COLUMN_NAME_TITLE, FeedEntry.COLUMN_NAME_SUBTITLE };String selection = null;String[] selectionArgs = { String.valueOf(rowId) };if (rowId != -1) {// 通过条件查询selection = FeedEntry._ID + " = ?";} else {selectionArgs = null;}// How you want the results sorted in the resulting CursorString sortOrder = FeedEntry.COLUMN_NAME_TITLE + " DESC";Cursor cursor = db.query(FeedEntry.TABLE_NAME, // The table to queryprojection, // The columns to returnselection, // The columns for the WHERE clauseselectionArgs, // The values for the WHERE clausenull, // don't group the rowsnull, // don't filter by row groupssortOrder // The sort order);List<FeedEntryDb> feedEntryDbList = new ArrayList<FeedEntryDb>();while (cursor.moveToNext()) {FeedEntryDb feedEntryDb = new FeedEntryDb();long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(FeedEntry._ID));feedEntryDb.setEntryid(cursor.getString(cursor.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_ENTRY_ID)));feedEntryDb.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TITLE)));feedEntryDb.setSubtitle(cursor.getString(cursor.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_SUBTITLE)));feedEntryDbList.add(feedEntryDb);}cursor.close();db.close();return feedEntryDbList;}/*** 更新** @param feedEntry* @param rowId* @return*/public int update(FeedEntryDb feedEntryDb, int rowId) {SQLiteDatabase db = mFeedReaderDbHelper.getReadableDatabase();// New value for one columnContentValues values = new ContentValues();values.put(FeedEntry.COLUMN_NAME_TITLE, feedEntryDb.getTitle().toString());// Which row to update, based on the IDString selection = FeedEntry._ID + " = ?";String[] selectionArgs = { String.valueOf(rowId) };int count = db.update(FeedEntry.TABLE_NAME, values, selection,selectionArgs);db.close();return count;}/*** 删除** @param rowId* @return*/public int delete(int rowId) {SQLiteDatabase db = mFeedReaderDbHelper.getReadableDatabase();// Define 'where' part of query.String selection = FeedEntry._ID + " = ?";// Specify arguments in placeholder order.String[] selectionArgs = { String.valueOf(rowId) };// Issue SQL statement.int count = db.delete(FeedEntry.TABLE_NAME, selection, selectionArgs);db.close();return count;}}
方法调用
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889package com.xiaomolong.sqlitesample;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener {DatabaseManger mDatabaseManger;TextView textView;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById(R.id.textView);findViewById(R.id.btnAdd).setOnClickListener(this);findViewById(R.id.btnQuery).setOnClickListener(this);findViewById(R.id.btnUpdate).setOnClickListener(this);findViewById(R.id.btnDelete).setOnClickListener(this);mDatabaseManger = new DatabaseManger(this);}public void onClick(View v) {switch (v.getId()) {case R.id.btnAdd:for (int i = 0; i < 5; i++) {FeedEntryDb feedEntryDb = new FeedEntryDb();feedEntryDb.setEntryid(i + "");feedEntryDb.setTitle("title" + i + "");feedEntryDb.setSubtitle("subtitle" + i + "");mDatabaseManger.insert(feedEntryDb);}break;case R.id.btnQuery:List<FeedEntryDb> feedEntryDbList = mDatabaseManger.query(-1);String t = "";for (int i = 0; i < feedEntryDbList.size(); i++) {t = t + feedEntryDbList.get(i).getTitle() + "\n"+ feedEntryDbList.get(i).getSubtitle() + "\n\n";}textView.setText(t);break;case R.id.btnUpdate:FeedEntryDb feedEntryDb = new FeedEntryDb();feedEntryDb.setTitle("修改");Log.d("wxl", "count=" + mDatabaseManger.update(feedEntryDb, 1));break;case R.id.btnDelete:Log.d("wxl", "count=" + mDatabaseManger.delete(1));break;default:break;}}public boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}public boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}