接續"[android SQLite] SQLite 建立資料庫/新增table / 刪除 table",來試一下新增和查詢。

在主程式裡,改成這樣:

package com.example.test;

 

import static android.provider.BaseColumns._ID;

//呼叫DBHelper類別定義的常數

import static com.example.test.DBHelper.EMAIL;

import static com.example.test.DBHelper.NAME;

import static com.example.test.DBHelper.TABLE_NAME;

import static com.example.test.DBHelper.TEL;

 

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.Menu;

import android.widget.TextView;

 

public class MainActivity extends Activity {

   private DBHelper dbhelper = null;

   private TextView result = null;

 

   @Override

   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

 

      dbhelper = new DBHelper(this);

      dbhelper.close();    

      add(); //每次應用程式執行時,會新增一筆名為david的資料

      result = (TextView) findViewById(R.id.textView2);

      show(); //顯示資料內容

   }

 

   //新增資料 

   private void add(){

       SQLiteDatabase db = dbhelper.getWritableDatabase();

       ContentValues values = new ContentValues();

       values.put(NAME, "david");

       values.put(TEL, "03-21451745");

       values.put(EMAIL, "david@yahoo.com");

       db.insert(TABLE_NAME, null, values);

   }

 

   //顯示資料

   private void show(){

       Cursor cursor = getCursor();

       StringBuilder resultData = new StringBuilder("RESULT: \n");

       while(cursor.moveToNext()){

       int id = cursor.getInt(0);

       String name = cursor.getString(1);

       String tel = cursor.getString(2);

       String email = cursor.getString(3);

       resultData.append(id).append(": ");

       resultData.append(name).append(", ");

       resultData.append(tel).append(", ");

       resultData.append(email).append(", ");

       resultData.append("\n");

       }

       result.setText(resultData);

   }

 

   @SuppressWarnings("deprecation")

   private Cursor getCursor(){

       SQLiteDatabase db = dbhelper.getReadableDatabase();

       String[] columns = {_ID, NAME, TEL, EMAIL};

       Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);

       startManagingCursor(cursor);

       return cursor;

   }

 

   @Override

   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;

   }

}

 

執行結果:

 SQLiteSelectAdd  

 

arrow
arrow

    jcgogo 發表在 痞客邦 留言(0) 人氣()