1. 程式人生 > >資料儲存之SQLite

資料儲存之SQLite

dbHelper.java

package com.terry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class dbHelper extends SQLiteOpenHelper {

	private final static String DATABASE_NAME="sec_db";
	private final static int DATABASE_VERSION=1;
	private final static String TABLE_NAME="sec_pwd";
	public final static String FIELD_ID="_id"; 
	public final static String FIELD_TITLE="sec_Title";
	
	
	public dbHelper(Context context)
	{   
		/**
		 * 通過建構函式來建立資料庫,如果進入此函式,不存在此資料庫則建立,如果存在此資料庫則開啟連線,
		 * 只要進入此方法就可以用開啟的連接獲得getWritableDatabase()或getReadableDatabase()這兩個方法。
		 */
		super(context, DATABASE_NAME,null, DATABASE_VERSION);
		
	}
	
	
	 /**
	  * 一個數據庫中可以包含多個表,每一條資料都存在指定的表中,要建立可以通過 execSQL 方法來執行一條 SQL 語句。
	  */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		//建立了表名為“sec_pwd” 的資料表,表記憶體在一個 integer 型別的主鍵和一個 text 型別的欄位,並執行建立該表。
		String sql="Create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"
		+FIELD_TITLE+" text );";
		db.execSQL(sql);
		
		 
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
		db.execSQL(sql);
		onCreate(db);
	}
    
	/**
	 * 查詢資料
	 * @return
	 */
	public Cursor select()
	{
		SQLiteDatabase db=this.getReadableDatabase();
		Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null,  " _id desc");
	   
		return cursor;
	}
	/**
	 * 新增資料
	 * @param Title
	 * @return
	 */
	public long insert(String Title)
	{   
		/**
		 * 封裝了一個使用SQLite 的 insert 方法,向表中新增資料,但是insert 方法要求把資料都打包到 ContentValues 中,
		 *  ContentValue 其實可就是一個 HashTable,Key值是欄位名稱,Value 值是欄位的值。
		 * 通過 ContentValues 的put 方法就可以把資料庫放到 ContentValue 物件中,然後插入到表中去。
		 */
		SQLiteDatabase db=this.getWritableDatabase();
		ContentValues cv=new ContentValues(); 
		cv.put(FIELD_TITLE, Title);
		long row=db.insert(TABLE_NAME, null, cv);
		return row;
	}
	/**
	 * 刪除資料
	 * @param id
	 */
	public void delete(int id)
	{
		SQLiteDatabase db=this.getWritableDatabase();
		String where=FIELD_ID+"=?";
		String[] whereValue={Integer.toString(id)};
		db.delete(TABLE_NAME, where, whereValue);
	}
	
	/**
	 * 修改資料
	 * @param id
	 * @param Title
	 */
	public void update(int id,String Title)
	{
		SQLiteDatabase db=this.getWritableDatabase();
		String where=FIELD_ID+"=?";
		String[] whereValue={Integer.toString(id)};
		ContentValues cv=new ContentValues(); 
		cv.put(FIELD_TITLE, Title);
		db.update(TABLE_NAME, cv, where, whereValue);
	}
	
	
	
	
}

  這裡用到了Menu做功能按鈕,例項程式碼如下:

 package com.terry;


import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle; 
import android.view.Menu;  
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;


public class testDbActivity extends Activity {
	
	private dbHelper db;
	private Cursor myCursor;
	private ListView myListView;
	private EditText myEditText;
	private int _id;
	protected final static int MENU_ADD=Menu.FIRST;
	protected final static int MENU_EDIT=Menu.FIRST+1;
	protected final static int MENU_DELETE=Menu.FIRST+2;
	
	   @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		   super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ADD, 0, R.string.ADD);
		menu.add(Menu.NONE, MENU_EDIT, 0,R.string.EDIT);
		menu.add(Menu.NONE, MENU_DELETE, 0,R.string.DELETE);
		 return true;
	}
	
	   @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		super.onOptionsItemSelected(item); 
		switch (item.getItemId()) {
		case MENU_ADD:
			operation("add");
			break;
		case MENU_EDIT:
			operation("edit");
			break;
		case MENU_DELETE:
			operation("delete");
			break;
		default:
			break;
		}
		return true;
	}
	   
	   
	   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myEditText=(EditText)findViewById(R.id.EditText1);
        myListView=(ListView)findViewById(R.id.ListView1);
        db=new dbHelper(testDbActivity.this);
        myCursor=db.select();
        SimpleCursorAdapter adpater=new SimpleCursorAdapter(this
        		, R.layout.test, myCursor,
        		new String[]{dbHelper.FIELD_TITLE},
        		new int[]{R.id.topTextView});
        myListView.setAdapter(adpater);
        
        myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				myCursor.moveToPosition(arg2);
				_id=myCursor.getInt(0);
				myEditText.setText(myCursor.getString(1));
			}
		});
        
        
        myListView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				SQLiteCursor sc=(SQLiteCursor)arg0.getSelectedItem();
				_id=sc.getInt(0);
				myEditText.setText(sc.getString(1));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    }
    private void operation(String cmd)
    {
    	if(myEditText.getText().toString().equals(""))
    	return;
    	if(cmd=="add")
    		db.insert( myEditText.getText().toString());
    	if(cmd=="edit")
    		db.update(_id,  myEditText.getText().toString());
    	if(cmd=="delete")
    		db.delete(_id);
    	myCursor.requery();
    	myListView.invalidateViews();
    	myEditText.setText("");
    	_id=0;
    	
    }
    
   
    
    
    
    
    
    
    
}