TShopping

 找回密碼
 註冊
搜索
查看: 651|回復: 0

[教學] [Android智慧型手機設計_Ch8_3_SQLite新增功能]

[複製鏈接]
發表於 2013-6-26 20:50:41 | 顯示全部樓層 |閱讀模式
 
Push to Facebook Push to Plurk Push to Twitter 
1.jpg


存取SQLite資料庫的說明如下:


資料新增的說明如下:

1.呼叫getWritableDatabase()建立、開啟資料庫並回傳資料庫物件

SQLiteDatabase db = getWritableDatabase();

2.建立ContentValues物件儲存欲新增的資料
ContentValues values = new ContentValues()
3.呼叫ContentValues的put()新增資料到指定欄位內
values.put(COL_id, site.getId());
4.呼叫insert()新增資料,新增成功會回傳該資料列的ID;新增失敗則回傳-1
long rowId = db.insert(TABLE_NAME, null, values);


1.設計Ch8_3_InsertData.java

  1. package com.example.ch8_3_insertdata;
  2. import java.util.ArrayList;
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.view.Menu;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.TextView;
  11. import android.widget.Toast;

  12. public class Ch8_3_Insert extends Activity {
  13. EditText et1,et2,et3,et4;
  14. Button btn1,btn2,btn3,btn4;
  15. TextView tv2;
  16. DBHP dbHlp;
  17. ArrayList<Site> sites;
  18. int index=0;
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.main);
  22. connectDB();
  23. findViews();
  24. showSites(index);
  25. }
  26. private void connectDB() {
  27. if(dbHlp == null)
  28. dbHlp = new DBHP(this);
  29. dbHlp.fillDB();
  30. sites=dbHlp.getAllSites();
  31. }
  32. void findViews(){
  33. et1=(EditText)findViewById(R.id.editText1);
  34. et2=(EditText)findViewById(R.id.editText2);
  35. et3=(EditText)findViewById(R.id.editText3);
  36. et4=(EditText)findViewById(R.id.editText4);
  37. btn1=(Button)findViewById(R.id.button1);
  38. btn2=(Button)findViewById(R.id.button2);
  39. btn3=(Button)findViewById(R.id.button3);
  40. btn4=(Button)findViewById(R.id.button4);
  41. tv2=(TextView)findViewById(R.id.textView2);
  42. btn1.setOnClickListener(new OnClickListener(){

  43. @Override
  44. public void onClick(View v) {
  45. index=index+1;
  46. if(index>=sites.size())
  47. index=0;
  48. showSites(index);
  49. }} );
  50. btn2.setOnClickListener(new OnClickListener(){

  51. @Override
  52. public void onClick(View v) {
  53. index=index-1;
  54. if(index<0)
  55. index=sites.size()-1;
  56. showSites(index);
  57. }} );
  58. btn3.setOnClickListener(new OnClickListener(){

  59. public void onClick(View v) {
  60. String id=et1.getText().toString().trim();
  61. String name=et2.getText().toString().trim();
  62. String phoneNo=et3.getText().toString().trim();
  63. String address=et4.getText().toString().trim();
  64. if(id.length()<=0 || name.length()<=0)
  65. Toast.makeText(Ch8_2_BrowseData.this, "未輸入代號或名稱!", Toast.LENGTH_LONG).show();
  66. StringBuilder sb=new StringBuilder();
  67. Site site=new Site(id,name,phoneNo,address);
  68. long rowId=dbHlp.insertDB(site);
  69. if(rowId !=-1)
  70. sb.append("新增資料成功!");
  71. else
  72. sb.append("新增資料失敗!");
  73. Toast.makeText(Ch8_2_BrowseData.this, sb, Toast.LENGTH_LONG).show();
  74. sites=dbHlp.getAllSites();//再呼叫一次getAllSites()取得資料庫中最新的內容
  75. }} );
  76. btn4.setOnClickListener(new OnClickListener(){

  77. @Override
  78. public void onClick(View v) {
  79. et1.setText("");
  80. et2.setText("");
  81. et3.setText("");
  82. et4.setText("");
  83. }} );
  84. }
  85. void showSites(int index){
  86. if(sites.size()>0){
  87. tv2.setText((index+1)+"/"+sites.size()+getString(R.string.count));
  88. et1.setText(sites.get(index).getId());
  89. et2.setText(sites.get(index).getName());
  90. et3.setText(sites.get(index).getPhoneNo());
  91. et4.setText(sites.get(index).getAddress());
  92. }else{
  93. tv2.setText("0/0"+getString(R.string.count));
  94. et1.setText("");
  95. et2.setText("");
  96. et3.setText("");
  97. et4.setText("");
  98. }
  99. }
  100. }
複製代碼



2.設計DBHP.java
  1. package com.example.ch8_3_insertdata;

  2. import java.util.ArrayList;
  3. import android.content.ContentValues;
  4. import android.content.Context;
  5. import android.database.Cursor;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.database.sqlite.SQLiteDatabase.CursorFactory;
  8. import android.database.sqlite.SQLiteOpenHelper;

  9. public class DBHP extends SQLiteOpenHelper {
  10. private static final String DATABASE_NAME = "sites";
  11. private static final int DATABASE_VERSION = 1;
  12. private static final String TABLE_NAME = "sitesInfo";
  13. private static final String TABLE_CREATE =
  14. "CREATE TABLE " + TABLE_NAME + " (id TEXT NOT NULL,name TEXT NOT NULL,phoneNo TEXT, address TEXT, PRIMARY KEY (id)); ";
  15. public DBHP(Context context) {
  16. super(context, DATABASE_NAME, null, DATABASE_VERSION);
  17. }
  18. @Override
  19. public void onCreate(SQLiteDatabase db) {
  20. db.execSQL(TABLE_CREATE);
  21. }
  22. @Override
  23. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  24. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
  25. onCreate(db);
  26. }
  27. public void fillDB() {
  28. SQLiteDatabase db = getWritableDatabase();
  29. ContentValues[] values = new ContentValues[3];
  30. for(int i=0; i<values.length; i++)
  31. values[i] = new ContentValues();

  32. values[0].put("id", "yangmingshan");
  33. values[0].put("name", "陽明山國家公園管理處");
  34. values[0].put("phoneNo", "02-28613601");
  35. values[0].put("address", "台北市北投區竹子湖路1之20號");

  36. values[1].put("id", "yushan");
  37. values[1].put("name", "玉山國家公園管理處");
  38. values[1].put("phoneNo", "049-2773121");
  39. values[1].put("address", "南投縣水里鄉中山路一段300號");

  40. values[2].put("id", "taroko");
  41. values[2].put("name", "太魯閣國家公園管理處");
  42. values[2].put("phoneNo", "03-8621100");
  43. values[2].put("address", "花蓮縣秀林鄉258號");

  44. for(ContentValues row : values){
  45. db.insert(TABLE_NAME, null, row);
  46. }
  47. db.close();
  48. }
  49. public ArrayList<Site> getAllSites()
  50. {
  51. SQLiteDatabase db = getReadableDatabase();
  52. String columns[]={"id","name","phoneNo","address"};
  53. Cursor cursor =db.query(TABLE_NAME, columns, null, null, null, null, null);
  54. ArrayList<Site> sites = new ArrayList<Site>();
  55. while(cursor.moveToNext()){
  56. String id=cursor.getString(0);
  57. String name=cursor.getString(1);
  58. String phoneNo=cursor.getString(2);
  59. String address=cursor.getString(3);
  60. Site site=new Site(id,name,phoneNo,address);
  61. sites.add(site);
  62. }
  63. cursor.close();
  64. db.close();
  65. return sites;
  66. }
  67. public long insertDB(Site site)
  68. {
  69. SQLiteDatabase db = getWritableDatabase();
  70. ContentValues values = new ContentValues();
  71. values.put("id", site.getId());
  72. values.put("name", site.getName());
  73. values.put("phoneNo", site.getPhoneNo());
  74. values.put("address", site.getAddress());
  75. long rowId=db.insert(TABLE_NAME, null, values);
  76. return rowId;
  77. }
  78. }
複製代碼



3.設計Site.java
  1. package com.example.ch8_3_insertdata;

  2. public class Site {
  3. String id,name,phoneNo,address;
  4. Site(String id,String name,String phoneNo,String address)
  5. {
  6. this.id=id;
  7. this.name=name;
  8. this.phoneNo=phoneNo;
  9. this.address=address;
  10. }
  11. String getId(){
  12. return id;
  13. }
  14. String getName(){
  15. return name;
  16. }
  17. String getPhoneNo(){
  18. return phoneNo;
  19. }
  20. String getAddress(){
  21. return address;
  22. }
  23. }
複製代碼
加入更新及刪除功能
Ch8_3_InsertData.java

  1. btn5.setOnClickListener(new OnClickListener(){
  2.    public void onClick(View v) {
  3.     String id=et1.getText().toString().trim();
  4.     String name=et2.getText().toString().trim();
  5.     String phoneNo=et3.getText().toString().trim();
  6.     String address=et4.getText().toString().trim();
  7.     if(id.length()<=0 || name.length()<=0){
  8.      Toast.makeText(getApplicationContext(), "未輸入ID或NAME", Toast.LENGTH_SHORT).show();
  9.     }else{
  10.      Site site=new Site(id,name,phoneNo,address);
  11.      int rowId=dbHlp.updateDB(site);
  12.      if(rowId!=-1){
  13.       Toast.makeText(getApplicationContext(), "更新成功", Toast.LENGTH_SHORT).show();
  14.       sites=dbHlp.getAllSites();
  15.       showSites(index);
  16.      }else
  17.       Toast.makeText(getApplicationContext(), "更新失敗", Toast.LENGTH_SHORT).show();
  18.     }
  19.    }
  20.   });
  21.   btn6.setOnClickListener(new OnClickListener(){
  22.    public void onClick(View v) {
  23.     String id=et1.getText().toString().trim();
  24.     int count=dbHlp.deleteDB(id);
  25.     if(count!=-1){
  26.      Toast.makeText(getApplicationContext(), "刪除成功", Toast.LENGTH_SHORT).show();
  27.     }else
  28.      Toast.makeText(getApplicationContext(), "刪除失敗", Toast.LENGTH_SHORT).show();
  29.     sites=dbHlp.getAllSites();
  30.     index=0;
  31.     showSites(index);
  32.    }
  33.   });
複製代碼
DBHP.java


  1. public int updateDB(Site site){
  2.   SQLiteDatabase db=getWritableDatabase();
  3.   ContentValues values=new ContentValues();
  4.   values.put("id", site.getId());
  5.   values.put("name", site.getName());
  6.   values.put("phoneNo", site.getPhoneNo());
  7.   values.put("address", site.getAddress());
  8.   String whereClause="id='"+site.getId()+"'";
  9.   int rowId=db.update(TABLE_NAME, values, whereClause, null);
  10.   return rowId;
  11. }
  12. public int deleteDB(String id){
  13.   SQLiteDatabase db=getWritableDatabase();
  14.   
  15.   String whereClause="id='"+id+"'";
  16.   int rowId=db.delete(TABLE_NAME, whereClause, null);
  17.   return rowId;
  18. }
複製代碼



 

臉書網友討論
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2016-12-9 15:59 , Processed in 0.056512 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表