Android数据库存储(绿豆通讯录)

 

 数据库存储

原理及说明

1. SQLite的特点:SQLite是Android自带的一个轻量级的数据库,他运算速度快,占用资源少,支持基本SQL语法。SQLite数据库可以存储应用程序中的大量数据,并对数据进行管理和维护。

2数据库的创建:创建一个继承自SQLiteOpenHelper的类,并在该类中实现OnCreate()方法和onUpgrade()方法。其中OnCreate()在第一次创建数据库时调用,用于初始化表结构;onUpgrade()在数据表进行修改的时候进行触发。

3. SQLite添加数据基本步骤如下:

(1)使用getWritableDatabase()方法获取可读写SQLiteDatabse对象;

(2)创建ContentValues对象;

(3)加将数据添加到ContentValues对象

(4)调用insert()方法完成数据的添加

4. SQLite修改数据基本步骤如下:

(1)使用getWritableDatabase()方法获取可读写SQLiteDatabse对象;

(2)创建ContentValues对象;

(3)加将数据添加到ContentValues对象

(4)调用update()方法完成数据的修改

5. SQLite删除数据基本步骤如下:

(1)使用getWritableDatabase()方法获取可读写SQLiteDatabse对象;

(2)调用delete()方法完成数据的添加

6. SQLite查询数据基本步骤如下:

(1)通过调用query()方法获取查询数据,返回集是一个Cursor游标;

(2)对Cursor游标集合进行操作,获取对应的数据。

7. SQLite中的事务具体包含以下步骤:

(1)db.beginTransaction()实现开启数据库事务;

(2)db.setTransactionSuccessful()设置事务标志为成功,当事务结束时,提交事务;

(3)db.endTransaction(); 关闭数据库事务

 

内容

1. 创建Android studio项目工程,使用数据库存储对应的数据,并实现数据的新增、修改、删除、查询等操作。

 

程序设计

通讯录设计:

Activity_main.xml设计:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/ll_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ll_phone"
        android:layout_alignStart="@+id/ll_btn">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓  名 :"
            android:textColor="#283593"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入姓名"
            android:textColorHint="#424242"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ll_btn"
        android:layout_alignStart="@+id/ll_name"
        android:layout_alignLeft="@+id/ll_name"
        android:layout_marginBottom="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电  话 :"
            android:textColor="#283593"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入手机号码"
            android:textColorHint="#424242"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ll_btn"
        android:layout_alignStart="@+id/ll_phone"
        android:layout_alignLeft="@+id/ll_phone"
        android:layout_marginBottom="30dp">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="地址:"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/et_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入地址"
            android:textColorHint="#37474F"
            android:textSize="16sp"
            tools:ignore="TouchTargetSizeCheck" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true">

        <Button
            android:id="@+id/btn_add"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#B9B9FF"
            android:text="添加"
            android:textColor="#0D47A1"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_query"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#DCB5FF"
            android:text="查询"
            android:textColor="#1B5E20"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_update"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="2dp"
            android:layout_weight="1"
            android:background="#E6CAFF"
            android:text="修改"
            android:textColor="#455A64"
            android:textSize="18sp" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#ACD6FF"
            android:text="删除"
            android:textColor="#455A64"
            android:textSize="18sp" />
    </LinearLayout>

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/ll_btn"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="5dp"
        android:divider="#d9d9d9"
        android:dividerHeight="2dp"></ListView>
    <!--    <TextView-->
    <!--        android:id="@+id/tv_show"-->
    <!--        android:layout_width="match_parent"-->
    <!--        android:layout_height="wrap_content"-->
    <!--        android:layout_below="@+id/ll_btn"-->
    <!--        android:layout_marginTop="25dp"-->
    <!--        android:textSize="20sp" />-->

 

 

 

List_item.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="wrap_content">

    <!-- 定义一个用于显示头像的ImageView -->
    <ImageView
        android:id="@+id/item_image"
        android:layout_width="66px"
        android:layout_height="66px"
        android:layout_margin="8dp"
        android:background="@drawable/ic_launcher_background" />

    <!-- 定义一个竖直方向的LinearLayout-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="3sp"
            android:text="我是姓名组件。"
            android:textColor="#00FFFF"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/item_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是电话组件。"
            android:textColor="#7FFFAA"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/item_address"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="我是地址组件。"
            android:textColor="#FF000000"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

 

 

 

 

 

创建MyHelper.java类实现SQLite库帮助:

package cn.itcast.directory1;

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

class MyHelper extends SQLiteOpenHelper {
    public MyHelper(Context context) {
        super(context, "itcast.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), phone VARCHAR(20),address VARCHAR(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

 

 

MainActivity实现:

package cn.itcast.directory1;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    MyHelper myHelper;
    private EditText mEtName;
    private EditText mEtPhone;
    //    private TextView mTvShow;
    private Button mBtnAdd;
    private Button mBtnQuery;
    private Button mBtnUpdate;
    private Button mBtnDelete;

    private ListView mList;
    private EditText mEtAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHelper = new MyHelper(this);
        init();//初始化控件
    }

    private void init() {
        mEtName = (EditText) findViewById(R.id.et_name);
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mEtAddress = (EditText) findViewById(R.id.et_address);
//        mTvShow = (TextView) findViewById(R.id.tv_show);
        mBtnAdd = (Button) findViewById(R.id.btn_add);
        mBtnQuery = (Button) findViewById(R.id.btn_query);
        mBtnUpdate = (Button) findViewById(R.id.btn_update);
        mBtnDelete = (Button) findViewById(R.id.btn_delete);
        mBtnAdd.setOnClickListener(this);
        mBtnQuery.setOnClickListener(this);
        mBtnUpdate.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);

        mList = (ListView) findViewById(R.id.lv);
    }

    @Override
    public void onClick(View v) {
        String name;
        String phone;
        String address;
        SQLiteDatabase db;
        ContentValues values;
        switch (v.getId()) {
            case R.id.btn_add: //添加数据
                name = mEtName.getText().toString();
                phone = mEtPhone.getText().toString();
                address = mEtAddress.getText().toString();
                db = myHelper.getWritableDatabase();//获取可读写SQLiteDatabse对象
                values = new ContentValues();       // 创建ContentValues对象
                values.put("name", name);           // 将数据添加到ContentValues对象
                values.put("phone", phone);
                values.put("address", address);
                db.insert("information", null, values);
                Toast.makeText(this, "信息已添加", Toast.LENGTH_SHORT).show();
                db.close();
                break;
            case R.id.btn_query: //查询数据
                Toast.makeText(this, "query", Toast.LENGTH_SHORT).show();
                db = myHelper.getReadableDatabase();
                Cursor cursor = db.query("information", null, null, null, null, null, null);
//                if (cursor.getCount() == 0) {
//                    //mTvShow.setText("");
//                    Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
//                } else {
//                    cursor.moveToFirst();
//                    mTvShow.setText("Name :  " + cursor.getString(1) + "  ;Tel :  " + cursor.getString(2));
//                    System.out.println("\n" + "Name :  " + cursor.getString(1) + "  ;Tel :  " + cursor.getString(2));
//                }
//                while (cursor.moveToNext()) {
//                    System.out.println("\n" + "Name :  " + cursor.getString(1) + "  ;Tel :  " + cursor.getString(2));
//                    //mTvShow.append("\n" + "Name :  " + cursor.getString(1) + "  ;Tel :  " + cursor.getString(2));
//                }


                SimpleCursorAdapter spcAdapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor,
                        new String[]{"name", "phone","address"}, new int[]{R.id.item_name, R.id.item_phone,R.id.item_address});
                mList.setAdapter(spcAdapter);


                //cursor.close();
                //db.close();
                break;
            case R.id.btn_update: //修改数据
                db = myHelper.getWritableDatabase();
                values = new ContentValues();       // 要修改的数据
                values.put("phone", phone = mEtPhone.getText().toString());
                values.put("address", address= mEtAddress.getText().toString());
                db.update("information", values, "name=?",
                        new String[]{mEtName.getText().toString()}); // 更新并得到行数
                Toast.makeText(this, "信息已修改", Toast.LENGTH_SHORT).show();
                db.close();
                break;
            case R.id.btn_delete: //删除数据
                db = myHelper.getWritableDatabase();
                db.delete("information", null, null);
                Toast.makeText(this, "信息已删除", Toast.LENGTH_SHORT).show();
//                mTvShow.setText("");
                db.close();
                break;
        }
    }

}

 

运行图:

17675348dad1200026f64fb38787ee575f9faf0f?

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敗北97

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值