android SQLite数据库使用实例

Wesley13
• 阅读 657

创建数据库帮助类DbHelper.java:

package com.example.db;

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

public class DbHelper extends SQLiteOpenHelper {

    public DbHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table if not exists tb_people"+
                "(_id integer primary key autoincrement,"+
                "name varchar(20),"+
                "phone varchar(12),"+
                "mobile varchar(12),"+
                "email varchar(30))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

}

主布局文件:

ch9_sqlmain.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="所有联系人:"
        android:textSize="15px"/>
    <LinearLayout android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView android:layout_width="40px"
            android:layout_height="wrap_content"
            android:text="编号"/>
        <TextView android:layout_width="50px"
            android:layout_height="wrap_content"
            android:text="姓名"/>
        <TextView android:layout_width="80px"
            android:layout_height="wrap_content"
            android:text="电话"/>
        <TextView android:layout_width="80px"
            android:layout_height="wrap_content"
            android:text="手机"/>
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="电子信箱"/>
    </LinearLayout>
    <ListView android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/list_people"/>

</LinearLayout>

编写ListView的Item显示布局文件ch9_peoplelist.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView android:id="@+id/id"
        android:layout_width="40px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/name"
        android:layout_width="50px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/phone"
        android:layout_width="80px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/mobile"
        android:layout_width="80px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    

</LinearLayout>

主活动类SqlMainActivity.java:

package com.example.ch9;

import com.example.baseexample.R;
import com.example.db.DbHelper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class SqlMainActivity extends Activity {
    private ListView list_people;
    private DbHelper dbhelper;
    private SQLiteDatabase db;
    
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ch9_sqlmain);
        
        list_people = (ListView)findViewById(R.id.list_people);
        
        dbhelper = new DbHelper(this, "Db_People", null, 1);
        
        db = dbhelper.getReadableDatabase();
        Cursor c = db.query("tb_people", new String[]{"_id","name","phone","mobile","email"}, null, null, null, null, null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.ch9_peoplelist, c, new String[]{"_id","name","phone","mobile","email"}, new int[]{R.id.id,R.id.name,R.id.phone,R.id.mobile,R.id.email});
        
        this.list_people.setAdapter(adapter);
        this.registerForContextMenu(list_people);
    }
    
    public boolean onCreateOptionsMenu(Menu menu){
        menu.add(Menu.NONE,Menu.FIRST+1,1,"添加").setIcon(android.R.drawable.ic_menu_add);
        menu.add(Menu.NONE,Menu.FIRST+1,2,"退出").setIcon(android.R.drawable.ic_menu_delete);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
        case Menu.FIRST+1:
            Intent intent = new Intent();
            intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
            startActivity(intent);
            break;
        case Menu.FIRST+2:finish();
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    
    public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
        menu.setHeaderIcon(R.drawable.ic_launcher);
        menu.add(0,3,0,"修改");
        menu.add(0, 4, 0, "删除");
    }
    
    public boolean onContextItemSelected(MenuItem item){
        AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
        switch(item.getItemId()){
        case 3:
            String name=((TextView)menuInfo.targetView.findViewById(R.id.name)).getText().toString();
            String phone=((TextView)menuInfo.targetView.findViewById(R.id.phone)).getText().toString();
            String mobile=((TextView)menuInfo.targetView.findViewById(R.id.mobile)).getText().toString();
            String email=((TextView)menuInfo.targetView.findViewById(R.id.email)).getText().toString();
            Intent intent = new Intent();
            intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
            Bundle bundle = new Bundle();
            bundle.putLong("id", menuInfo.id);
            bundle.putString("name", name);
            bundle.putString("phone", phone);
            bundle.putString("mobile", mobile);
            bundle.putString("email", email);
            intent.putExtras(bundle);
            startActivity(intent);
            break;
        case 4:
            dbhelper = new DbHelper(this,"Db_People",null,1);
            db = dbhelper.getWritableDatabase();
            db.delete("tb_people", "_id=?", new String[]{menuInfo.id+""});
            break;
        }
        
        return true;
    }
    
}

布局文件ch9_addpeople.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="用户名"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_name"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="联系电话"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_phone"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="手机"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_mobile"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="电子信箱"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_email"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bt_save"
            android:text="保存"
            android:layout_weight="1"/>
        <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bt_cancel"
            android:text="取消"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>

创建活动AddPeopleActivity.java:

package com.example.ch9;

import com.example.baseexample.R;
import com.example.db.DbHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddPeopleActivity extends Activity {
    private EditText edt_name;
    private EditText edt_phone;
    private EditText edt_mobile;
    private EditText edt_email;
    private Button bt_save;
    String name,phone,mobile,email;
    DbHelper dbhelper;
    SQLiteDatabase db;
    Bundle bundle;
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ch9_addpeople);
        
        edt_name=(EditText)findViewById(R.id.edt_name);
        edt_phone=(EditText)findViewById(R.id.edt_phone);
        edt_mobile=(EditText)findViewById(R.id.edt_mobile);
        edt_email=(EditText)findViewById(R.id.edt_email);
        bt_save = (Button)findViewById(R.id.bt_save);
        
        bundle = this.getIntent().getExtras();
        if(bundle!=null){
            edt_name.setText(bundle.getString("name"));
            edt_phone.setText(bundle.getString("phone"));
            edt_mobile.setText(bundle.getString("mobile"));
            edt_email.setText(bundle.getString("email"));
        }
        
        bt_save.setOnClickListener(new Button.OnClickListener(){

            @Override
            public void onClick(View v) {
                name = edt_name.getText().toString();
                phone = edt_phone.getText().toString();
                mobile = edt_mobile.getText().toString();
                email = edt_email.getText().toString();
                
                ContentValues value = new ContentValues();
                value.put("name", name);
                value.put("phone", phone);
                value.put("mobile", mobile);
                value.put("email", email);
                
                DbHelper dbhelper = new DbHelper(AddPeopleActivity.this,"Db_People",null,1);
                SQLiteDatabase db = dbhelper.getWritableDatabase();
                long status;
                if(bundle!=null){
                    status = db.update("tb_people", value, "_id=?", new String[]{bundle.getLong("id")+""});
                }else{
                    status = db.insert("tb_people", null, value);
                }
                if(status!=-1){
                    Toast.makeText(AddPeopleActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(AddPeopleActivity.this, "保存失败", Toast.LENGTH_LONG).show();
                }
            }
            
        });
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这