增加改查——android数据库篇二

大家好,昨天晚上发布了数据库SQLITE第一篇,今天早上到现在为止,上班也没有什么心思(主要是过年了,大家都是这样子,人嘛总在公司总像一个样子),所以我从早上到现在一直在写ANDROID,现在是数据库篇二。感觉一个字"累"!

对了,还有一件事,版主和我讲,用JAVA的HIBERNATE反射机制,能不能生成增加改查方法。我还在查看资料。估计能的话,我会在年后写出来。不行我也没办法。起码努力了就行。对吧。,感谢大家。

 

 

让我们看一下图,希望大家喜欢!

让我们看这里面所写的部份代码。

下面我们来看一下代码的实现业务方法。

package com.smart;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqliteHelper extends SQLiteOpenHelper {

 public static final String TB_NAME = "llb";
//构造方法
 public SqliteHelper(Context context, String name, CursorFactory factory,
   int version) {
  
  super(context, name, null, 1);
 }
 
 /**
  * 创建新数据库表
  */
 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("CREATE TABLE IF NOT EXISTS " +
    TB_NAME + "(" +
    Bean.ID + " integer primary key," +
    Bean.CITY + " varchar(10)," +
    Bean.CODE + " varcher(20)"+
    ")");
 }
 
 /**
  * 当检测与前一次创建数据库版本不一样时,先删除表再创建新表
  */
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS " + TB_NAME);
  onCreate(db);
 }
 
 /**
  * 变更列名
  * @param db
  * @param oldColumn
  * @param newColumn
  * @param typeColumn
  */
 public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){
  try{
   db.execSQL("ALTER TABLE " +
     TB_NAME + " CHANGE " +
     oldColumn + " "+ newColumn +
     " " + typeColumn
   );
  }catch(Exception e){
   e.printStackTrace();
  }
 }


}

BEAN类

package com.smart;


public class Bean {
 public static final String ID = "_id";
 public static final String CITY = "city";
 public static final String CODE = "code";
 
 private String id;
 private String city;
 private String code;
 
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }

}

Activity类

package com.smart;

 

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 本例实现SQLite数据库增加、删除、修改、模糊查询操作。这里不是最好的实现方法,
 * *  
 *  llb988@126.com 
 */
public class Main extends Activity {
 private static String DB_NAME = "smart.db";
 private static int DB_VERSION = 1;
 private static int POSTION;
 private ListView listview;
 private Cursor cursor;
 private SQLiteDatabase db;
 private SqliteHelper dbHelper;
 private ListAdapter listAdapter;
 
 private EditText etCity;
 private EditText etCode;
 private Button bt_add;
 private Button bt_modify;
 private Button bt_query;
 
 private List<Bean> cityList = new ArrayList<Bean>();
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     
     etCity = (EditText) findViewById(R.id.etCity);
     etCode = (EditText) findViewById(R.id.etCode);
     bt_add = (Button) findViewById(R.id.bt_add);
     bt_modify = (Button) findViewById(R.id.bt_modify);
     bt_query = (Button) findViewById(R.id.bt_query);
     
     try{
      /* 初始化并创建数据库 */
      dbHelper = new SqliteHelper(this, DB_NAME, null, DB_VERSION);
      /* 创建表 */
      db = dbHelper.getWritableDatabase(); //调用SQLiteHelper.OnCreate()         
         /* 查询表,得到cursor对象 */
         cursor = db.query(SqliteHelper.TB_NAME, null, null, null, null, null, Bean.CODE + " DESC");
         cursor.moveToFirst();
         while(!cursor.isAfterLast() && (cursor.getString(1) != null)){   
          Bean city = new Bean();
          city.setId(cursor.getString(0));
          city.setCity(cursor.getString(1));
          city.setCode(cursor.getString(2));
          cityList.add(city);
          cursor.moveToNext();
          //得到数据。
         }
     }catch(IllegalArgumentException e){
      //当用SimpleCursorAdapter装载数据时,表ID列必须是_id,否则报错column '_id' does not exist
      e.printStackTrace();
      //当版本变更时会调用SQLiteHelper.onUpgrade()方法重建表 注:表以前数据将丢失
      ++ DB_VERSION;
      dbHelper.onUpgrade(db, --DB_VERSION, DB_VERSION);
//      dbHelper.updateColumn(db, SQLiteHelper.ID, "_"+SQLiteHelper.ID, "integer");
     }
     listview = (ListView)findViewById(R.id.listView);
     listAdapter = new ListAdapter();
     listview.setAdapter(listAdapter);
     listview.setOnItemClickListener(new ListView.OnItemClickListener(){
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int postion,
     long arg3) {
    setSelectedValues(postion);
   }      
     });
     
     /* 插入表数据并ListView显示更新 */
     bt_add.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View arg0) {
    if(etCity.getText().length() > 1 && etCode.getText().length() >1){
     ContentValues values = new ContentValues();
     values.put(Bean.CITY, etCity.getText().toString().trim());
     values.put(Bean.CODE, etCode.getText().toString().trim());
     //插入数据 用ContentValues对象也即HashMap操作,并返回ID号
     Long cityID = db.insert(SqliteHelper.TB_NAME, Bean.ID, values);
     Bean city = new Bean();
     city.setId(""+cityID);
           city.setCity(etCity.getText().toString().trim());
           city.setCode(etCode.getText().toString().trim());
           cityList.add(city);
           listview.setAdapter(new ListAdapter());
           resetForm();
    }
   }
  });
     
     /* 查询表,模糊条件查询 */
     bt_query.setOnClickListener(new Button.OnClickListener(){
      @Override
      public void onClick(View view) {
       cityList.removeAll(cityList);
       String sql = null;
       String sqlCity = etCity.getText().length() > 0 ? Bean.CITY + " like '%" + etCity.getText().toString().trim() + "%'" : "";       
       String sqlCode = etCode.getText().length() > 0 ? Bean.CITY + " like '%" + etCity.getText().toString().trim() + "%'" : "";
       if( (!"".equals(sqlCity)) && (!"".equals(sqlCode)) ){
        sql = sqlCity + " and" + sqlCode;
       }else if(!"".equals(sqlCity)){
        sql = sqlCity;
       }else if(!"".equals(sqlCode)){
        sql = sqlCode;
       }
       cursor = db.query(true, SqliteHelper.TB_NAME,
         new String[]{Bean.ID, Bean.CITY, Bean.CODE},
         sql,
         null, null, null, null, null);
       cursor.moveToFirst();
       while(!cursor.isAfterLast() && (cursor.getString(1) != null)){ 
        Bean city = new Bean();
              city.setId(cursor.getString(0));
              city.setCity(cursor.getString(1));
              city.setCode(cursor.getString(2));
              cityList.add(city);
        cursor.moveToNext();
       }
       listview.setAdapter(new ListAdapter());
       resetForm();
      }
     });
     
     /* 修改表数据 */
     bt_modify.setOnClickListener(new Button.OnClickListener(){
   @Override
   public void onClick(View arg0) {
    ContentValues values = new ContentValues();
    values.put(Bean.CITY, etCity.getText().toString().trim());
    values.put(Bean.CODE, etCode.getText().toString().trim());
    db.update(SqliteHelper.TB_NAME, values, Bean.ID + "=" + cityList.get(POSTION).getId(), null);
    cityList.get(POSTION).setCity(etCity.getText().toString().trim());
    cityList.get(POSTION).setCode(etCode.getText().toString().trim());
    listview.setAdapter(new ListAdapter());
    resetForm();
   }
  });
    }
   
    /* 设置选中ListView的值 */
    public void setSelectedValues(int postion){
     POSTION = postion;
  etCity.setText(cityList.get(postion).getCity());
  etCode.setText(cityList.get(postion).getCode());
    }
   
    /* 重值form */
    public void resetForm(){
  etCity.setText("");
  etCode.setText("");
    }
   
    @Override
    protected void onDestroy() {
     db.delete(SqliteHelper.TB_NAME, null, null);
     super.onDestroy();
    }
   
    private class ListAdapter extends BaseAdapter{
     public ListAdapter(){
      super();
     }
  @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return cityList.size();
  }

  @Override
  public Object getItem(int postion) {
   // TODO Auto-generated method stub
   return postion;
  }

  @Override
  public long getItemId(int postion) {
   // TODO Auto-generated method stub
   return postion;
  }

  @Override
  public View getView(final int postion, View view, ViewGroup parent) {
   view = getLayoutInflater().inflate(R.layout.listview, null);
   TextView tv = (TextView) view.findViewById(R.id.tvCity);
   tv.setText("" + cityList.get(postion).getCity());
   TextView bu = (TextView) view.findViewById(R.id.btRemove);
   bu.setText(R.string.delete);
   bu.setId(Integer.parseInt(cityList.get(postion).getId()));
   
   /* 删除表数据 */
   bu.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View view) {
     try{
      db.delete(SqliteHelper.TB_NAME, Bean.ID + "=" + view.getId(), null);
      cityList.remove(postion);
      listview.setAdapter(new ListAdapter());      
     }catch(Exception e){
      e.printStackTrace();
     }
    }
   });
   return view;
   //返回
  }
    }
}

 

posted on 2011-01-27 15:59  llb988  阅读(1255)  评论(0编辑  收藏  举报

导航