2011年12月2日 星期五

SQLite的新增和刪除

首先先針對XML作設計

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TextView android:id="@+id/show"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="姓名:" />
    <EditText android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView android:id="@+id/tphone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="電話:" />
    <EditText android:id="@+id/phone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView android:id="@+id/taddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="住址:" />
    <EditText android:id="@+id/address"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <LinearLayout android:id="@+id/LinerLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <Button android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="新增"
        />
     <Button android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清除"
        />
     <Button android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除"
        />
    </LinearLayout>
</LinearLayout>

package com.demo.android.SQLiteA;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SQLiteAActivity extends Activity {

static String TABLE_NAME = "Users"; //表格名稱
static String NAME = "name"; //姓名
static String ADDRESS = "address";     //住址
static String PHONE = "phone"; //電話

DBConnection dbconn;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        final TextView show=(TextView)findViewById(R.id.show);
        //insert Button
        OnClickListener OnInsertClick = null;
        OnClickListener OnDeleteClick = null;
     
        dbconn = new DBConnection(this);
        //取得可寫入的資料庫
        SQLiteDatabase db = dbconn.getWritableDatabase();
     
        //查詢資料表
        Cursor c = db.query(TABLE_NAME, new String[] {NAME,PHONE,ADDRESS}, null, null, null, null, null);
        //移至第一筆資料
c.moveToFirst();
//讀取查詢結果所有資料
String result ="";
for(int i=0; i<c.getCount();i++){
result = result +"("+c.getString(0)+", "+c.getString(1)+", "+c.getString(2)+")";
c.moveToNext();
}
show.setText(result);

        c.close();
        //設定Onclick函數
        OnInsertClick=new OnClickListener(){

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    //ContentValues 是負責儲存一對值,但是它儲存的一個是String類型,其他是基本類型
    ContentValues values = new ContentValues();
    values.put(NAME, ((EditText)findViewById( R.id.username)).getText().toString());
    values.put(PHONE, ((EditText)findViewById( R.id.phone)).getText().toString());
    values.put(ADDRESS, ((EditText)findViewById( R.id.address)).getText().toString());
    //執行寫入資料庫
    SQLiteDatabase db = dbconn.getWritableDatabase();
    db.insert(TABLE_NAME, null, values);
    db.close();
    onCreate(savedInstanceState);
    }
       
        };
       
        //設定ClearClick函數
         OnClickListener OnClearClick=new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(show!=null){
show.setText(" ");
}
}
               
        };
        //設定DeleteClick函數
        OnDeleteClick=new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//按下[Delete]按鈕時,刪除一筆資料
String where =NAME+"="+((EditText)findViewById( R.id.username)).getText().toString();
SQLiteDatabase db = dbconn.getWritableDatabase();
try{
db.delete(TABLE_NAME, "name=?" , new String[]{((EditText)findViewById( R.id.username)).getText().toString()});

}catch(Exception ex){
                     ex.printStackTrace();
        }

db.close();
onCreate(savedInstanceState);

}
       
        };
     
        //建立insertBtnOnclick事件
        Button insertBtn=(Button)findViewById(R.id.insert);
        insertBtn.setOnClickListener(OnInsertClick);
        //建立clearBtnOnClick事件
        Button clearBtn=(Button)findViewById(R.id.clear);
        clearBtn.setOnClickListener(OnClearClick);
        //建立deleteBtnOnClick事件
        Button deleteBtn=(Button)findViewById(R.id.delete);
        deleteBtn.setOnClickListener(OnDeleteClick);
     
    }
 
 實作 onCreate onUpgrade 方法。onCreate 是當資料庫建立時會執行的方法,我們可以在這裡建立資料表或設定預設的資料庫參數。onUpgrade 是當資料庫的版本不同時,會執行的方法。如果新舊版本的資料表不同,我們可以有2種方式處理。第一種是把舊的資料表刪除,再建立新的資料表,但是這樣原有的資料就會消失,因此第二種方法是將舊的資料表按照新的表格格式儲存,存完之後再刪除舊的。 SQLiteOpenHelper 實作code如下:

  //建立資料庫PhoneDB和Table:Users
    public static class DBConnection extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "PhoneDB";
private static final int DATABASE_VERSION = 2;
private DBConnection(Context ctx) {
//context=內容物件 DATABASE_NAME=傳入的資料庫名稱 null=複雜查詢時使用 DATABASE_VERSION=資料庫版本
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
//建立資料表
String sql = "CREATE TABLE " + TABLE_NAME + " ("
+ NAME + " text not null, "
+ PHONE + " text not null, "
+ ADDRESS + " text not null" + ");";

db.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.android.Message"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
   
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".MessageActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
<!-- 新增可以發送簡訊的權限 -->
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
</manifest>

8 則留言:

  1. 老師 我想問一下 如果 在切換畫面中黑屏的話是捨麼問題導致的呢??
    還有如果自己做遊戲 圖片不用別人的 那程式碼有參考別人的 也有標明出處 這樣有觸犯道著作權嗎??

    回覆刪除
  2. 你的頁面這段setContentView(R.layout.main)是.main還是.你目前的網頁,程式碼如果參考別人的,建議你還是多少要修正一些,不可以一字不漏的,可以參考但是一字不漏也算抄襲,還是要小心

    回覆刪除
  3. 我的activity是setContentView(R.layout.main)其他頁面是setContentView(new MySurfaceView(this));我不太懂他弄這個的意思

    回覆刪除
  4. 正確來說第二頁應該是setContentView(R.layout.你新增頁的名稱才對)

    回覆刪除
  5. 第二頁是遊戲畫面了 所以 還是要做xml檔嗎??

    回覆刪除
  6. 老師 您好
    想請問這有完整範例檔嗎??

    回覆刪除