--------------------------------------------AndroidManifest.xml----------------------------------

<manifestxmlns:android="http://schemas.android.com/apk/res/android"

package="com.ch20"

android:versionCode="1"

android:versionName="1.0">

<uses-sdk

android:minSdkVersion="10"

android:targetSdkVersion="15"/>

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

<activity

android:name=".ListViewActivity"

android:label="@string/title_activity_main">

<intent-filter>

<actionandroid:name="android.intent.action.MAIN"/>

<categoryandroid:name="android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

</application>

</manifest>

--------------------------------------------Layoutactivity_main.xml----------------------------

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/LinearLayout1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<Button

android:id="@+id/add_id"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="添加数据"/>

<Button

android:id="@+id/delete_id"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="删除数据"/>

<Button

android:id="@+id/edit_id"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="修改数据"/>

<Button

android:id="@+id/qyery_id"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="查询数据"/>

<ListView

android:id="@+id/show_result"

android:layout_width="fill_parent"

android:layout_height="wrap_content">

</ListView>

</LinearLayout>

--------------------------------------------Layoutlist_item.xml---------------------------------

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/LinearLayout1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="horizontal">

<TextView

android:id="@+id/view_id"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="id....."/>

<TextView

android:id="@+id/view_name"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="name....."/>

</LinearLayout>

--------------------------------------------Layoutlist_input.xml--------------------------------

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/LinearLayout1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<TextView

android:id="@+id/view_id"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="学生编号"/>

<EditText

android:id="@+id/stu_id"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

<TextView

android:id="@+id/view_name"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="学生姓名"/>

<EditText

android:id="@+id/stu_name"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

</LinearLayout>

--------------------------------------------ListViewActivity.java----------------------------------

packagecom.ch20;

importjava.util.HashMap;

importjava.util.List;

importandroid.app.Activity;

importandroid.app.AlertDialog;

importandroid.app.AlertDialog.Builder;

importandroid.content.ContentValues;

importandroid.content.DialogInterface;

importandroid.os.Bundle;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

importandroid.widget.EditText;

importandroid.widget.ListView;

importandroid.widget.SimpleAdapter;

/**

*

*项目名称:com.ch20

*类名称:ListViewActivity

*类描述:CRUD

*创建人:方勇

*创建时间:2012-12-4上午9:37:39

*Copyright(c)方勇-版权所有

*/

publicclassListViewActivityextendsActivityimplementsOnClickListener{

privateListViewlisView;

privateList<HashMap<String,Object>>list;

privateButtonaddBtn,deleteBtn,editBtn,queryBtn;

privateSimpleAdaptersimpleAdapter;

privateDBHelperdbHelper;

@Override

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

findViews();

setListeners();

dbHelper=newDBHelper(this);

init();

}

@Override

publicvoidonClick(Viewv){

switch(v.getId()){

caseR.id.add_id:

buildDialog_input().show();

break;

caseR.id.delete_id:

//deleteDialog_input().show();

break;

caseR.id.edit_id:

buildDialog_update().show();

break;

caseR.id.qyery_id:

break;

}

}

/*实例化UI*/

privatevoidfindViews(){

addBtn=(Button)findViewById(R.id.add_id);

deleteBtn=(Button)findViewById(R.id.delete_id);

editBtn=(Button)findViewById(R.id.edit_id);

queryBtn=(Button)findViewById(R.id.qyery_id);

lisView=(ListView)findViewById(R.id.show_result);

}

/*设置监听*/

privatevoidsetListeners(){

addBtn.setOnClickListener(this);

deleteBtn.setOnClickListener(this);

editBtn.setOnClickListener(this);

queryBtn.setOnClickListener(this);

}

/*初始化数据*/

privatevoidinit(){

list=StudentBean.getInstance().findList(dbHelper);

simpleAdapter=newSimpleAdapter(this,list,R.layout.list_item,newString[]{"id","name"},newint[]{

R.id.view_id,R.id.view_name});

lisView.setAdapter(simpleAdapter);

}

/*添加数据对话框*/

privateAlertDialogbuildDialog_input(){

/*获取布局文件*/

LayoutInflaterlayoutInflater=LayoutInflater.from(this);

finalViewview=layoutInflater.inflate(R.layout.list_input,null);

/*弹出对话框,输入数据*/

Builderbuild=newAlertDialog.Builder(this);

build.setTitle("输入学生信息");//标题

build.setView(view);//内容

//确定按钮

build.setPositiveButton("submit",newDialogInterface.OnClickListener(){

@Override

publicvoidonClick(DialogInterfacedialog,intwhich){

/*获取数据*/

EditTextfiled_id=(EditText)view.findViewById(R.id.stu_id);

EditTextfiled_name=(EditText)view.findViewById(R.id.stu_name);

/*保存数据*/

//dbHelper.open();

//ContentValuesvalues=newContentValues();

//values.put("id",Integer.parseInt(filed_id.getText().toString()));

//values.put("name",filed_name.getText().toString());

//Log.i("a07","id="+filed_id.getText().toString());

//Log.i("a07","name="+filed_name.getText().toString());

//longsize=dbHelper.insert("stu",values);

//dbHelper.close();

ContentValuesvalues=newContentValues();

values.put(StudentBean.STU_ID,Integer.parseInt(filed_id.getText().toString()));

values.put(StudentBean.STU_NAME,filed_name.getText().toString());

longsize=StudentBean.getInstance().save(dbHelper,values);

/*追加数据*/

if(size>0){

HashMap<String,Object>map=newHashMap<String,Object>();

map.put(StudentBean.STU_ID,Integer.parseInt(filed_id.getText().toString()));

map.put(StudentBean.STU_NAME,filed_name.getText().toString());

list.add(map);

/*更新UI*/

simpleAdapter.notifyDataSetChanged();

}

}

});

build.setNegativeButton("cancel",null);

returnbuild.create();

}

/*修改数据对话框*/

privateAlertDialogbuildDialog_update(){

/*获取布局文件*/

LayoutInflaterlayoutInflater=LayoutInflater.from(this);

finalViewview=layoutInflater.inflate(R.layout.list_input,null);

/*弹出对话框,输入数据*/

Builderbuild=newAlertDialog.Builder(this);

build.setTitle("输入学生信息");//标题

build.setView(view);//内容

//确定按钮

build.setPositiveButton("submit",newDialogInterface.OnClickListener(){

@Override

publicvoidonClick(DialogInterfacedialog,intwhich){

/*获取数据*/

EditTextfiled_id=(EditText)view.findViewById(R.id.stu_id);

EditTextfiled_name=(EditText)view.findViewById(R.id.stu_name);

/*保存数据*/

// dbHelper.open();

// ContentValuesvalues=newContentValues();

// values.put("id",Integer.parseInt(filed_id.getText().toString()));

// values.put("name",filed_name.getText().toString());

// Log.i("a07","id="+filed_id.getText().toString());

// Log.i("a07","name="+filed_name.getText().toString());

// //条件

// StringwhereClause="id=?";

// //条件值

// String[]whereArgs=newString[]{filed_id.getText().toString()};

// longsize=dbHelper.update("stu",whereClause,whereArgs,values);

// dbHelper.close();

HashMap<String,Object>oldValues=newHashMap<String,Object>();

oldValues.put(StudentBean.STU_ID,Integer.parseInt(filed_id.getText().toString()));

longsize=StudentBean.getInstance().update(dbHelper,oldValues,newString[]{filed_name.getText().toString()});

if(size>0){

HashMap<String,Object>map=null;

Stringid=filed_id.getText().toString();

for(inti=0;i<list.size();i++){

HashMap<String,Object>mmap=list.get(i);

if(mmap.get("id").toString().equals(id)){

map=list.get(i);

break;

}

}

map.put("id",Integer.parseInt(filed_id.getText().toString()));

map.put("name",filed_name.getText().toString());

//list.add(map);

/*更新UI*/

simpleAdapter.notifyDataSetChanged();

}

}

});

build.setNegativeButton("cancel",null);

returnbuild.create();

}

}

--------------------------------------------DBHelper.java-----------------------------------------

packagecom.ch20;

importandroid.content.ContentValues;

importandroid.content.Context;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.database.sqlite.SQLiteOpenHelper;

/**

*

*项目名称:com.ch20

*类名称:DBHelper

*类描述:数据库操作工具类

*创建人:方勇

*创建时间:2012-12-4上午8:50:40

*Copyright(c)方勇-版权所有

*/

publicclassDBHelper{

/*DDL,定义数据结构*/

privateDataBaseHelperdbHelper;

/*DML,数据库操作*/

privateSQLiteDatabasedb;

/*数据库名*/

privatefinalstaticStringDATABASE_NAME="a07.db3";

/*版本号*/

privatefinalstaticintDATABASE_VERSION=1;

/*上下文*/

privateContextmcontext;

publicDBHelper(Contextmcontext){

super();

this.mcontext=mcontext;

}

/*静态内部类,针对DDL*/

privatestaticclassDataBaseHelperextendsSQLiteOpenHelper{

publicDataBaseHelper(Contextcontext){

super(context,DATABASE_NAME,null,DATABASE_VERSION);

}

/*创建表结构*/

@Override

publicvoidonCreate(SQLiteDatabasedb){

// db.execSQL("createtableifnotexistsstu(idintegerprimarykey,nametext)");

db.execSQL(StudentBean.getInstance().sql$createTable());

// db.execSQL("insertintostuvalues(1,'a1')");

// db.execSQL("insertintostuvalues(2,'a2')");

}

/*针对数据库升级*/

@Override

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){

}

}

/*打开数据库,如果已经打开就使用,否则创建*/

publicDBHelperopen(){

dbHelper=newDataBaseHelper(mcontext);

db=dbHelper.getWritableDatabase();

returnthis;

}

/*关闭数据库*/

publicvoidclose(){

db.close();//先关DML

dbHelper.close();//DDL

}

/*插入*/

publiclonginsert(StringtableName,ContentValuesvalues){

returndb.insert(tableName,null,values);

}

/**

*

*更新

*

*@paramtableName表名

*@paramwhereClause条件

*@paramwhereArgs条件值

*@paramvalues更新值

*@return更新的条数

*

*/

publiclongupdate(StringtableName,StringwhereClause,String[]whereArgs,ContentValuesvalues){

returndb.update(tableName,values,whereClause,whereArgs);

}

/*删除*/

publicbooleandelete(StringtableName,StringwhereClause,String[]whereArgs){

returndb.delete(tableName,whereClause,whereArgs)>0;

}

/**

*

*查询,多条记录

*

*@paramtableName表名

*@paramcolumns列名

*@paramselection条件

*@paramselectionArgs条件值

*@paramgroupBy分组

*@paramhaving过滤

*@paramorderBy排序

*@paramlimit分页(2,3),从第二条记录开始,向下取三条记录

*@return动态游标

*

*/

publicCursorfindList(StringtableName,String[]columns,Stringselection,String[]selectionArgs,StringgroupBy,

Stringhaving,StringorderBy,Stringlimit){

returndb.query(tableName,columns,selection,selectionArgs,groupBy,having,orderBy,limit);

}

/**

*

*精确查询,返回一条数据

*

*@paramtableName表名

*@paramcolumns列名

*@paramselection条件

*@paramselectionArgs条件值

*@paramgroupBy分组

*@paramhaving过滤

*@paramorderBy排序

*@paramlimit分页(2,3),从第二条记录开始,向下取三条记录

*@return动态游标

*

*/

publicCursorfindInfo(StringtableName,String[]columns,Stringselection,String[]selectionArgs,StringgroupBy,

Stringhaving,StringorderBy,Stringlimit){

Cursorcursor=db.query(tableName,columns,selection,selectionArgs,groupBy,having,orderBy,limit);

while(cursor.moveToNext()){

cursor.moveToFirst();

}

returncursor;

}

/*执行sql方法*/

publicvoidexecuteSql(Stringsql){

db.execSQL(sql);

}

}

--------------------------------------------StudentBean.java-------------------------------------

packagecom.ch20;

importjava.util.ArrayList;

importjava.util.HashMap;

importjava.util.List;

importandroid.content.ContentValues;

importandroid.database.Cursor;

/**

*

*项目名称:com.ch20

*类名称:StudentBean

*类描述:业务逻辑Bean

*创建人:方勇

*创建时间:2012-12-6上午11:57:16

*Copyright(c)方勇-版权所有

*/

publicclassStudentBean{

privatestaticStudentBeanstudentBean=null;

/*表名*/

publicfinalstaticStringTABLE_NAME="stu";

/*表对应的字段*/

publicfinalstaticStringSTU_ID="id";

publicfinalstaticStringSTU_NAME="name";

/*单例模式*/

publicstaticStudentBeangetInstance(){

if(null==studentBean){

studentBean=newStudentBean();

}

returnstudentBean;

}

/*DDL操作*/

//创建表结构SQL

publicStringsql$createTable(){

return"createtableifnotexistsstu(idintegerprimarykey,nametext)";

}

//删除表结构SQL

publicStringsql$dropTable(){

return"droptableifexistsstu(idintegerprimarykey,nametext)";

}

/*DML操作*/

/*插入*/

publiclongsave(DBHelperdbHelper,ContentValuesvalues){

dbHelper.open();

longsize=dbHelper.insert(TABLE_NAME,values);

dbHelper.close();

returnsize;

}

/**

*

*更新

*

*@paramdbHelper

*@paramoldValues一般为Map,可根据自己的实际情况调整

*@paramnewValues一般为String[],可根据自己的实际情况调整

*@return更新的记录

*

*/

publiclongupdate(DBHelperdbHelper,HashMap<String,Object>oldValues,String[]newValues){

dbHelper.open();

ContentValuesvalues=newContentValues();

values.put(STU_NAME,newValues[0]);

longsize=dbHelper.update(TABLE_NAME,"id=?",newString[]{oldValues.get(STU_ID).toString()},values);

dbHelper.close();

returnsize;

}

/*删除*/

publiclongdelete(DBHelperdbHelper,StringwhereArs,HashMap<String,Object>values){

return0;

}

/*获取数据库集合数据*/

publicList<HashMap<String,Object>>findList(DBHelperdbHelper){

dbHelper.open();

Cursorcursor=dbHelper.findList(TABLE_NAME,null,null,null,null,null,null,null);

Listlist=cursor2List(cursor);

dbHelper.close();

returnlist;

}

/*游标转换为集合*/

privateList<HashMap<String,Object>>cursor2List(Cursorcursor){

Listlist=newArrayList<HashMap<String,Object>>();

/*有记录*/

while(cursor.moveToNext()){

HashMap<String,Object>map=newHashMap<String,Object>();

intid=cursor.getInt(cursor.getColumnIndex(STU_ID));

Stringname=cursor.getString(cursor.getColumnIndex(STU_NAME));

map.put(STU_ID,id);

map.put(STU_NAME,name);

list.add(map);

}

returnlist;

}

}

--------------------------------------------效果----------------------------------------------------

添加数据

修改数据

<!--EndFragment-->

更多相关文章

  1. Android(安卓)鲜为人知的 8 个小秘密
  2. ch023 Android(安卓)ContentProvider(第一部分,单元测试)
  3. android sd卡读取数据库
  4. Android(安卓)存储选项之 SQLiteDatabase 创建过程源码分析
  5. Android(安卓)存储优化系列专题
  6. Android(安卓)图表开源框架之MPAndroidChart LineChart折线图(六)
  7. Android架构组件- Room数据库的使用
  8. Android(安卓)之不要滥用 SharedPreferences(上)
  9. Android(安卓)存储选项之 SQLite 优化那些事儿

随机推荐

  1. 深入SQL Server中定长char(n)与变长varch
  2. 深入SQL Server 跨数据库查询的详解
  3. SQL SERVER函数之深入表值函数的处理分析
  4. SQLServer:探讨EXEC与sp_executesql的区
  5. 深入SQL SERVER合并相关操作Union,Except
  6. 深入SQL截取字符串(substring与patindex)
  7. SQLServer2000 报1053错误(服务没有及时
  8. SQL Server中删除重复数据的几个方法
  9. sql 语句练习与答案
  10. 解析如何用SQL语句在指定字段前面插入新