码迷,mamicode.com
首页 > 数据库 > 详细

实验8 SQLite数据库操作

时间:2016-05-11 23:22:58      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

课程名称

基于Android平台移动互联网开发

实验日期

2016年4月15日

实验项目名称

数独游戏界面设计

实验地点

S3010

实验类型

□验证型    √设计型    □综合型

学  时

 

一、实验目的及要求(本实验所涉及并要求掌握的知识点)

【目的】

   设计一个个人通讯录,掌握Android平台下的数据库开发,该个人通讯录主要包括联系人列表和联系人详细信息等界面。

【要求】

程序主界面是通讯录的目录显示手机上联系人的名称。点击联系人的姓名可以显示联系人的详细信息。在按了MEMU键之后会弹出菜单栏。单击菜单栏上的按钮可以添加联系人和删除联系人.

二、实验环境(本实验所使用的硬件设备和相关软件)

(1)PC机

(2)操作系统:Windows XP

(3)软件: Eclipse, JDK1.6,Android SDK,ADT

三、实验内容及步骤

(1)确定数据库的数据结构。本程序只要一张表,该表的内容及说明如下表所示

字段名称

数据类型

说明

字段名称

数据类型

声明

_id

Integer

所插入记录的编号

name

varchar

联系人名称

phone

Varchar

联系人的固定电话

mobile

varchar

手机号码

 

Email

Varchar

联系人的邮箱的地址

post

varchar

联系人固话

addr

varchar

联系认的地址

comp

varchar

联系人所在地

(2) 在res/drawable-mdpi目录下拷入程序要用的图标

1)        新建工程

2)        修改布局文件activity_main.xml

3)       定义字符串资源string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ContantsApp</string>
    
    <string name="please_input_password">请输入通讯录密码:</string>
    <string name="ok">确定</string>
    
    <string name="login_success">恭喜,登陆成功!</string>
    <string name="error_password">您输入的密码错误,请重新输入!</string>
    
    <string name="password_manage">通讯录密码管理:</string>
    <string name="new_password">新密码:</string>
    <string name="repeat_password">再一次:</string>
    
    <string name="password_is_null">输入密码为空,请输入密码!</string>
    <string name="password_set_success">密码设置成功!</string>
    <string name="password_change_success">密码修改成功!</string>
    <string name="password_isnot_equal">两次输入的密码不一致,请重新输入密码!</string>
    
    <string name="title">通讯录列表</string>
    <string name="not_dbcursor_values">数据库中没有记录,请点击菜单新建通讯录!</string>
    
    <string name="contantsName">姓名:</string>
    <string name="contantsPhone">固定电话:</string>
    <string name="contantsMobile">移动电话:</string>
    <string name="contantsEmail">电子邮件:</string>
    <string name="contantsPost">邮政编码:</string>
    <string name="contantsAddr">通讯地址:</string>
    <string name="contantsComp">公司地址:</string>
    
    <string name="menu_add">增加</string>
    <string name="menu_change">修改密码</string>
</resources>

 4)开发布局文件activity_main.xml用于显示联系人列表。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="@string/title"
            android:textSize="24px"
            android:textColor="@color/text"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/title"
            />
        </LinearLayout>
        <ListView    
            android:id="@+id/db_listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:choiceMode="singleChoice"
            /> 
</LinearLayout>

(5)layout目录下新建一个contants_detail.xml,用于显示联系人详细信息,代码参考如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    >
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        >                            <!-- 显示联系人姓名线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsName"
            />
        <EditText
            android:id="@+id/etName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
         </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                            <!-- 显示联系人固定电话的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="center_vertical|left"
            android:text="@string/contantsPhone"
            />
        <EditText
            android:id="@+id/etPhone"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:phoneNumber="true"
            />
         </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                                        <!-- 显示联系人手机号码的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsMobile"
            />
        <EditText
            android:id="@+id/etMobile"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:phoneNumber="true"
            />
         </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                                        <!-- 显示联系人电子邮件的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsEmail"
            />
        <EditText
            android:id="@+id/etEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
         </LinearLayout> 
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                                        <!-- 显示联系人邮编的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsPost"
            />
        <EditText
            android:id="@+id/etPost"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
         </LinearLayout>  
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                                        <!-- 显示联系人通信地址的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsAddr"
            />
        <EditText
            android:id="@+id/etAddr"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
         </LinearLayout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >                                        <!-- 显示联系人公司的线性布局 -->
        <TextView
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:textSize="18px"
            android:textColor="@color/text"
            android:layout_gravity="left|center_vertical"
            android:text="@string/contantsComp"
            />
        <EditText
            android:id="@+id/etComp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
         </LinearLayout>
     <ImageButton
         android:id="@+id/detailSave"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:src="@drawable/save"
         />
</LinearLayout>

5)开发数据库辅助类MyOpenHelper类,新建一个MyOpenHelper.java。其中的框架代码如下

package com.cn.daming.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper{

    private final static String DATABASE_NAME = "personal_contacts";
    private final static int DATABASE_VERSION = 1;
    private final static String TABLE_NAME = "contants";
    public static final String ID="_id";       //ID
    public static final String NAME="name";       //名称
    public static final String PHONE="phone";  //固定电话
    public static final String MOBILE="mobile";//手机号码
    public static final String EMAIL="email";  //电子邮件地址
    public static final String POST="post";       //邮政编码
    public static final String ADDR="addr";       //通信地址
    public static final String COMP="comp";       //公司
    
    public final static String LOGIN_TABLE_NAME = "contantslogin";
    public final static String LOGIN_USER = "admin";
    public final static String LOGIN_PWD = "password";
    
    public DBOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table "+TABLE_NAME+" ("
        + ID + " integer primary key autoincrement,"
        + NAME + " varchar,"
        + PHONE+" varchar,"
        + MOBILE + " varchar,"
        + EMAIL + " varchar,"
        + POST + " varchar,"
        + ADDR + " varchar,"
        + COMP + " varchar)";
        db.execSQL(sql);
        
        sql = "create table "+LOGIN_TABLE_NAME+" ("
        +LOGIN_USER+" text, "
        +LOGIN_PWD+" text )";
        db.execSQL(sql);        
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        String sql = "drop table if exists "+TABLE_NAME;
        db.execSQL(sql);

        sql = "drop table if exists "+LOGIN_TABLE_NAME;
        db.execSQL(sql);
        onCreate(db);        
    }

    public Cursor selectContants(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
        return cursor;
    }
    
    public long insertContants(String[] strArray){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(NAME, strArray[0]);
        cv.put(PHONE, strArray[1]);
        cv.put(MOBILE, strArray[2]);
        cv.put(EMAIL, strArray[3]);    
        cv.put(POST, strArray[4]);
        cv.put(ADDR, strArray[5]);
        cv.put(COMP, strArray[6]);
        return db.insert(TABLE_NAME, null, cv);
    }
    
    public void deleteContants(String id){
        SQLiteDatabase db = this.getWritableDatabase();
        String where = ID+"=?";
        String[] whereValues = {id};
        db.delete(TABLE_NAME, where, whereValues);
    }
    
    public int updateContants(String id,String[] strArray){
        SQLiteDatabase db = this.getWritableDatabase();
        String where = ID+"=?";
        String[] whereValues = {id};
        ContentValues cv = new ContentValues();
        cv.put(NAME, strArray[0]);
        cv.put(PHONE, strArray[1]);
        cv.put(MOBILE, strArray[2]);
        cv.put(EMAIL, strArray[3]);    
        cv.put(POST, strArray[4]);
        cv.put(ADDR, strArray[5]);
        cv.put(COMP, strArray[6]);
        return db.update(TABLE_NAME, cv, where, whereValues);
    }
    
    public Cursor getContants(String id){
        SQLiteDatabase db = this.getReadableDatabase();
        String where = ID+"=?";
        String[] whereValues = {id};
        Cursor cursor = db.query(TABLE_NAME, null, where, whereValues, null, null, null);
        return cursor;
    }
    
    public long insertPwd(String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(LOGIN_USER, LOGIN_USER);
        cv.put(LOGIN_PWD, password);
        return db.insert(LOGIN_TABLE_NAME, null, cv);
    }
    
    public int updatePwd(String password){
        SQLiteDatabase db = this.getWritableDatabase();
        String where = LOGIN_USER+"=?";
        String[] whereValues = {LOGIN_USER};
        ContentValues cv = new ContentValues();
        cv.put(LOGIN_PWD, password);
        return db.update(LOGIN_TABLE_NAME, cv, where, whereValues);
    }

    public String getPwd(){
        SQLiteDatabase db = this.getReadableDatabase();
        String where = LOGIN_USER+"=?";
        String[] whereValues = {LOGIN_USER}; 
        Cursor cursor = db.query(LOGIN_TABLE_NAME, null, where, whereValues, null, null, null);
        if(cursor.moveToFirst()){
            return cursor.getString(cursor.getColumnIndex(LOGIN_PWD));
        }else{
            return "";
        }
    }
}

 6)接下来便进入MainActivity端的开发,实现数据库增加、删除、修改记录等操作

 7)新建一个Activity名字叫DetailActivity.java,实现联系人详细信息显示功能。

四、实验结果(本实验源程序清单及运行结果或实验结论、实验设计图)

代码:

MainActivity.java

package com.cn.daming;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.cn.daming.adapter.ContantsAdapter;
import com.cn.daming.databases.DBOpenHelper;

public class MainActivity extends Activity {

    private DBOpenHelper dbOpenHelper;
    private ContantsAdapter contantsAdapter;
    private ListView dbListView;
    private Cursor cursor;
    
    final int MENU_ADD = Menu.FIRST;
    final int MENU_CHANGE = Menu.FIRST+1;
    
    private List<String> ids;
    private List<String> names;
    private List<String> phones;
    AlertDialog dialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dbOpenHelper = new DBOpenHelper(this);
        dbListView = (ListView)findViewById(R.id.db_listview);
        refreshDBOpenHelper();

        dbListView.setOnItemClickListener(new OnItemClickListener(){

            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                Intent intent= new Intent();
                intent.putExtra("cmd", 0);    
                String contants_id = ids.get(position);//0代表查询联系人,1代表添加联系人
                intent.putExtra("id", contants_id);
                intent.setClass(MainActivity.this, DetailContantsActivity.class);
                startActivity(intent);
            }
        });
        
        dbListView.setOnItemLongClickListener(new OnItemLongClickListener(){

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    final int position, long arg3) {
                dialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle("提示!!")
                .setMessage("确定要删除这条记录?")
                .setPositiveButton("确定",
                 new DialogInterface.OnClickListener()
                 {
                     public void onClick(DialogInterface dialog, int whichButton)
                     {
                         String contants_id = ids.get(position);
                         dbOpenHelper.deleteContants(contants_id);
                         dbOpenHelper.close();
                         Toast.makeText(MainActivity.this, "正在删除数据库,请稍后。。。", Toast.LENGTH_LONG).show();
                         refreshDBOpenHelper();
                         contantsAdapter.notifyDataSetChanged();
                     }
                     })
                 .setNegativeButton("取消",new DialogInterface.OnClickListener()
                 {
                      public void onClick(DialogInterface dialog, int whichButton)
                      {
                         dialog.dismiss();
                      }
                  }).show();
                return false;
            }
        });
    }
    
    @Override
    protected void onResume() {
        refreshDBOpenHelper();    
        contantsAdapter.notifyDataSetChanged();
        super.onResume();
    }

    public void refreshDBOpenHelper(){
        cursor = dbOpenHelper.selectContants();
        ids = new ArrayList<String>();
        names = new ArrayList<String>();
        phones = new ArrayList<String>();
        
        int count = cursor.getCount();
        if(count>0){
            for(int i=0;i<count;i++){
                cursor.moveToPosition(i);
                ids.add(cursor.getString(0));
                names.add(cursor.getString(1));
                phones.add(cursor.getString(2));
            }
        }else{
            Toast.makeText(this, R.string.not_dbcursor_values, Toast.LENGTH_SHORT).show();
        }
        contantsAdapter = new ContantsAdapter(this,names,phones);
        dbListView.setAdapter(contantsAdapter);
        cursor.close();
        dbOpenHelper.close();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_ADD, 0, R.string.menu_add)
            .setIcon(R.drawable.add);    //add - add_button 
        menu.add(0, MENU_CHANGE, 0, R.string.menu_change)
            .setIcon(R.drawable.modify);        //add -add_change_password
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){        //
        case MENU_ADD:            //press change add button
            Intent add_intent= new Intent(this,DetailContantsActivity.class);
            add_intent.putExtra("cmd", 1);
            startActivity(add_intent);
            break;
        case MENU_CHANGE:    //press change password button
            Intent change_password_intent = new Intent(MainActivity.this,PasswordManage.class);
            startActivityForResult(change_password_intent,0);
            break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Login.java

package com.cn.daming;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cn.daming.databases.DBOpenHelper;

public class Login extends Activity {

    private DBOpenHelper db;
    private EditText et;
    private Button login_button;
    private String password;
    
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        
        db = new DBOpenHelper(this);
        password = db.getPwd();
        db.close();
        if(password.equals("")){
            Intent intent = new Intent(Login.this,PasswordManage.class);
            startActivity(intent);
            finish();
            return;
        }
        setContentView(R.layout.login);
        
        et = (EditText)findViewById(R.id.login_password);
        login_button = (Button)findViewById(R.id.note_login);
        
        login_button.setOnClickListener(new Button.OnClickListener(){
    
            public void onClick(View v) {
                String input_pwd = et.getText().toString();
                if(password.equals(input_pwd)){
                    Toast.makeText(Login.this, R.string.login_success, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Login.this,MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(Login.this, R.string.error_password, Toast.LENGTH_LONG).show();
                    et.setText("");
                }
            }
            
        });
    }
}

DetailContantsAcyivity.java

package com.cn.daming;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.cn.daming.databases.DBOpenHelper;

public class DetailContantsActivity extends Activity{

    Cursor cursor;
    DBOpenHelper dbOpenHelper;
    int id = -1;                    
    int [] textIds ={
        R.id.etName,
        R.id.etPhone,
        R.id.etMobile,
        R.id.etEmail,
        R.id.etPost,
        R.id.etAddr,
        R.id.etComp
    };
    EditText [] textArray;
    ImageButton saveButton;    //save Button
    int status = -1;    //0表示查看信息,1表示添加联系人,2表示修改联系人
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contants_detail);
        textArray = new EditText[textIds.length];
        for(int i=0;i<textIds.length;i++){
            textArray[i] = (EditText)findViewById(textIds[i]);
        }
        initSaveImageButton();
        dbOpenHelper = new DBOpenHelper(this);
        Intent intent = getIntent();
        status = intent.getExtras().getInt("cmd");    
        switch(status){
        case 0:            
            String contants_id = intent.getExtras().getString("id");        
            cursor = dbOpenHelper.getContants(contants_id);
            int count = cursor.getCount();
            if(count == 0){            
                Toast.makeText(this, "对不起,没有找到指定的联系人!", Toast.LENGTH_LONG).show();
            }
            else{                 
                cursor.moveToFirst();             
                textArray[0].setText(cursor.getString(1));            //设置姓名框中的内容
                textArray[1].setText(cursor.getString(2));            //设置固话框中的内容
                textArray[2].setText(cursor.getString(3));            //设置手机号码框中的内容
                textArray[3].setText(cursor.getString(4));            //设置电子邮件框中的内容
                textArray[4].setText(cursor.getString(5));            //设置电子邮件框中的内容
                textArray[5].setText(cursor.getString(6));            //设置电子邮件框中的内容
                textArray[6].setText(cursor.getString(7));            //设置电子邮件框中的内容
            }
            cursor.close();
            dbOpenHelper.close();
            break;
        case 1:                    //新建详细人信息
            for(EditText et:textArray){
                et.getEditableText().clear();        //清空各个EditText控件中内容
            }
            break;
        }
    }
    
    public void initSaveImageButton()
    {
        saveButton = (ImageButton)findViewById(R.id.detailSave);
        saveButton.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                String [] strArray = new String[textArray.length];
                for(int i=0;i<strArray.length;i++){
                    strArray[i] = textArray[i].getText().toString().trim();    //获得用户输入的信息数组
                }
                if(strArray[0].equals("") || strArray[1].equals("")){
                    Toast.makeText(DetailContantsActivity.this, "对不起,请将姓名和电话填写完整!", Toast.LENGTH_LONG).show();
                }else{
                    switch(status){        //判断当前的状态
                    case 0:                //查询联系人详细信息时按下保存
                        updateContact(strArray);        //更新联系人信息
                        break;
                    case 1:                //新建联系人时按下保存按钮
                        insertContact(strArray);        //插入联系人信息
                        break;
                    }            
                }
            }
        });
    }
    
    public void insertContact(String [] strArray){
        long count = dbOpenHelper.insertContants(strArray);        //插入数据
        dbOpenHelper.close();
        if(count == -1){
            Toast.makeText(this, "添加联系人失败!", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(this, "添加联系人成功!", Toast.LENGTH_LONG).show();
        }
    }
    
    public void updateContact(String [] strArray){
        int count = dbOpenHelper.updateContants(id+"", strArray);    //更新数据库
        dbOpenHelper.close();
        if(count == 1){
            Toast.makeText(this, "修改联系人成功!", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(this, "修改联系人失败!", Toast.LENGTH_LONG).show();
        }
    }
}

PasswordManage.java

package com.cn.daming;

import com.cn.daming.databases.DBOpenHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class PasswordManage extends Activity {
    
    private EditText et1;
    private EditText et2;
    private Button button;
    private DBOpenHelper db;
    private int CHANGE_PWD_SUCCESS = 100;
    
    public void onCreate(Bundle bundle){
        super.onCreate(bundle);
        db = new DBOpenHelper(this);
        setContentView(R.layout.password_manage);
        
        et1 = (EditText)findViewById(R.id.new_password);
        et2 = (EditText)findViewById(R.id.repeat_password);
        button = (Button)findViewById(R.id.save_password);
        
        button.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View v) {
                String new_pwd = et1.getText().toString();
                String repeat_pwd = et2.getText().toString();
                if(new_pwd==null||new_pwd.equals("")){
                    Toast.makeText(PasswordManage.this, R.string.password_is_null, Toast.LENGTH_LONG).show();
                }else{
                    if(new_pwd.equals(repeat_pwd)){
                        if(db.getPwd().equals("")){
                            db.insertPwd(new_pwd);
                            Toast.makeText(PasswordManage.this, R.string.password_set_success, Toast.LENGTH_LONG).show();
                            toNoteList();
                        }else{
                            db.updatePwd(new_pwd);
                            Toast.makeText(PasswordManage.this, R.string.password_change_success, Toast.LENGTH_LONG).show();
                            PasswordManage.this.setResult(CHANGE_PWD_SUCCESS);
                            PasswordManage.this.finish();
                        }
                    }else{
                        Toast.makeText(PasswordManage.this, R.string.password_isnot_equal, Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }
    
    public void toNoteList(){
        Toast.makeText(PasswordManage.this, R.string.password_set_success, Toast.LENGTH_LONG);
        Intent intent = new Intent(PasswordManage.this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

}

ContantsAdapter.java

package com.cn.daming.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.cn.daming.R;

public class ContantsAdapter extends BaseAdapter {

    private List<String> names;
    private List<String> phones;
    private LayoutInflater inflater;
    private Context context;
    
    public ContantsAdapter(Context context,List<String> names ,List<String> phones){
        inflater = LayoutInflater.from(context);
        this.names = names;
        this.phones = phones;
        this.context = context;
    }
    
    public int getCount() {
        return names.size();
    }

    public Object getItem(int position) {
        return names.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View view, ViewGroup group) {
        ContantsHolder holder = new ContantsHolder();
        if(view==null){
            view = inflater.inflate(R.layout.contants_list_view, null);
            holder.contansName = (TextView)view.findViewById(R.id.name_textview);
            holder.contantsPhone = (TextView)view.findViewById(R.id.phone_textview);
            view.setTag(holder);
        }else{
            holder = (ContantsHolder)view.getTag();
        }
        holder.contansName.setText(names.get(position));
        holder.contantsPhone.setText(phones.get(position));
        return view;
    }

    public class ContantsHolder
    {
        private TextView contansName;
        private TextView contantsPhone;
    }
}

运行截图如下:

技术分享

技术分享

技术分享

技术分享

技术分享

五、实验总结(对本实验结果进行分析,实验心得体会及改进意见)

在这次实验过程中,现在程序实现了利用SQLite数据库的帮助类SQLiteOpenHelper 实现增删改查的功能,程序主界面是通讯录的目录显示手机上联系人的名称。点击联系人的姓名可以显示联系人的详细信息。单击MEMU键之后会弹出菜单栏,可以进行添加联系人以及重设登录密码。保存联系人退出后会有联系人列表,长时间点击联系人条目可以进行删除操作。通过参考资料和老师上课讲解梳理了部分知识难点,完成的挺顺利。

实验评语

 

实验成绩

 

指导教师签名:              年   月   日

 

实验8 SQLite数据库操作

标签:

原文地址:http://www.cnblogs.com/iTues/p/5483927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!