android的一个小实例,SQLiteDatabase的增删改查

一、简述

本文使用了一个简单的通讯录,一共有两页,代码没有优化,甚至有许多冗余代码,如果想要总体源码请私信我。

二、效果展示

                               

                               

 三、程序刚需

 本文只用了fresco库,做了图片的圆形处理

implementation("com.facebook.fresco:fresco:0.12.0")

 在AndroidManifest.xml文件中引入程序的电话权限,以及注册页面,具体信息如下。

以下是AndroidManifest.xml文件的内容

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TelephoneDirectoryApplication"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivityadd"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="tel" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission-sdk-23 android:name="android.permission.CALL_PHONE"/>

</manifest>

在通讯录页面使用了ListView标签而产生了listview.xml, listview.xml的布局效果如上图1显示。在处理每一条时,继承了ArrayAdapter<PersonEntity>类,继承类为PersonAdapter.java。数据传递使用了PersonEntity实体类。

listview.xml布局信息如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
    <LinearLayout
        android:id="@+id/liner9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/index_user_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="1"
            android:textSize="16dp"
            android:layout_marginTop="25dp"
            />

        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/profile"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="5dp"
            fresco:placeholderImage="@drawable/manold"
            fresco:roundAsCircle="true"/>


        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:layout_marginLeft="20dp"
            android:orientation="vertical">
            <TextView
                android:id="@+id/xingming1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="姓名:"
                android:textSize="22dp"
                android:layout_marginTop="10dp"
                android:textStyle="bold"
                />
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/phone2"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:text="电话号码:"
                    android:textSize="16dp"
                    android:layout_marginTop="3dp"
                    />
                <TextView
                    android:id="@+id/update_user"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="修改信息"
                    android:layout_marginLeft="20dp"/>
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
</LinearLayout>

 处理每一条数据,PersonAdapter.java继承了ArrayAdapter<PersonEntity>类,实现如下:

package com.example.telephonedirectoryapplication;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

public class PersonAdapter extends ArrayAdapter<PersonEntity> {
    public PersonAdapter(@NonNull Context context, int resource, @NonNull List<PersonEntity> objects) {
        super(context, resource, objects);
    }
    //每个子项被滚动到屏幕内的时候会被调用
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        PersonEntity person = getItem(position);//得到当前项的 Fruit 实例
        System.out.println("图片" + person.getImgAddress());
        //为每一个子项加载设定的布局
        View view= LayoutInflater.from(getContext()).inflate(R.layout.listview,parent,false);
        //分别获取 image view 和 textview 的实例
        SimpleDraweeView simpleDraweeView1 = view.findViewById(R.id.profile);
        TextView name = view.findViewById(R.id.xingming1);
        TextView phone = view.findViewById(R.id.phone2);
        TextView index_user_phone = view.findViewById(R.id.index_user_phone);


        simpleDraweeView1.setImageURI(Uri.parse("res://drawable/" + person.getImgAddress()));
        name.setText("姓名:" + person.getName().toString());
        phone.setText("电话号码:" + person.getPhone().toString());
        index_user_phone.setText("" + person.getId());

        TextView update_user = view.findViewById(R.id.update_user);
        update_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonAdapter.this.getContext(),MainActivityadd.class);

                intent.putExtra("update_user", "update_user");
                intent.putExtra("title_Image",person.getImgAddress());
                intent.putExtra("id",person.getId());
                intent.putExtra("name",person.getName());
                intent.putExtra("phone",person.getPhone());
                intent.putExtra("email",person.getEmail());
                intent.putExtra("address",person.getAddresspre());
                PersonAdapter.this.getContext().startActivity(intent);

            }
        });
        return view;
    }

}

PersonEntity实体类信息如下: 

package com.example.telephonedirectoryapplication;

public class PersonEntity {
    int id;
    String name;
    String phone;
    String email;
    String addresspre;
    int imgAddress;

    public PersonEntity(int id, String name, String phone, String email, String addresspre, int imgAddress) {
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.email = email;
        this.addresspre = addresspre;
        this.imgAddress = imgAddress;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public PersonEntity(String name, String phone, String email, String addresspre, int imgAddress) {
        this.name = name;
        this.phone = phone;
        this.email = email;
        this.addresspre = addresspre;
        this.imgAddress = imgAddress;
    }

    public PersonEntity() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddresspre() {
        return addresspre;
    }

    public void setAddresspre(String addresspre) {
        this.addresspre = addresspre;
    }

    public int getImgAddress() {
        return imgAddress;
    }

    public void setImgAddress(int imgAddress) {
        this.imgAddress = imgAddress;
    }

    @Override
    public String toString() {
        return "PersonEntity{" +
                "name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                ", addresspre='" + addresspre + '\'' +
                ", imgAddress=" + imgAddress +
                '}';
    }
}

四、布局信息

MainActivity.java活动类对应了activity_main.xml布局文件,具体信息如下

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:background="#FF0"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/txl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="通讯录"
            android:textSize="24dp" />
        <EditText
            android:id="@+id/search_name_phone"
            android:layout_width="260dp"
            android:layout_height="40dp"
            android:background="@drawable/kongxingyuan"
            android:paddingRight="40dp"
            android:layout_marginTop="-2dp"
            android:textSize="14dp"
            android:hint="输入搜索的信息(姓名/电话号)" />
        <ImageView
            android:id="@+id/name_phone_search"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginLeft="-40dp"
            android:layout_marginTop="5dp"
            android:src="@drawable/search_name_phone"/>

        <TextView
            android:id="@+id/addInformation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"
            android:textColor="#000"
            android:textSize="24dp"
            android:layout_marginTop="2dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="10dp"/>
    </LinearLayout>


    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout1" >
        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>



</androidx.constraintlayout.widget.ConstraintLayout>

 MainActivityadd.java活动类对应了activity_mainadd.xml布局文件,具体信息如下

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivityadd">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:background="#FF0"
        app:layout_constraintTop_toTopOf="parent">
        <TextView
            android:id="@+id/fanhuitext"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:text="返回"
            android:textSize="24dp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout1" >
            <ImageView
                android:id="@+id/zuojiantou"
                android:layout_width="80dp"
                android:layout_height="185dp"
                android:src="@drawable/zuojiantou"/>
            <com.facebook.drawee.view.SimpleDraweeView
                android:id="@+id/xuanzhe"
                android:layout_width="150dp"
                android:layout_height="150dp"
                android:layout_marginTop="15dp"
                android:gravity="center"
                fresco:placeholderImage="@drawable/manold"
                fresco:roundedCornerRadius="20dp"/>
            <ImageView
                android:id="@+id/youjiantou"
                android:layout_width="80dp"
                android:layout_height="185dp"
                android:src="@drawable/youjiantou" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        android:background="#00FFFF"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="30dp"
        fresco:roundedCornerRadius="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout2" >
        <TextView
            android:id="@+id/xinming"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:text="姓名:"
            android:layout_marginLeft="5dp"
            android:textSize="20dp" />
        <EditText
            android:id="@+id/name1"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="text"
            android:hint="姓名"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:background="@null" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="#00FFFF"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"
        fresco:roundedCornerRadius="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout3" >
        <TextView
            android:id="@+id/dhuanhaoma"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:text="电话号码:"
            android:layout_marginLeft="5dp"
            android:textSize="20dp" />
        <EditText
            android:id="@+id/phone1"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="phone"
            android:hint="电话号码"
            android:layout_marginLeft="20dp"
            android:background="@null" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#00FFFF"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginTop="10dp"
        fresco:roundedCornerRadius="10dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout4" >

    <LinearLayout
        android:id="@+id/linearLayout7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/youxiang"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:text="邮箱:"
            android:layout_marginLeft="5dp"
            android:textSize="20dp" />
        <EditText
            android:id="@+id/em"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:hint="邮箱"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:background="@null" />
    </LinearLayout>

        <View
            android:id="@+id/view4"
            android:layout_width="match_parent"
            android:layout_marginTop="-5dp"
            android:layout_height="1dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:background="#808080"/>
        <LinearLayout
            android:id="@+id/linearLayout8"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:id="@+id/shuozai"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                android:text="所在城市:"
                android:layout_marginLeft="5dp"
                android:textSize="20dp" />
            <EditText
                android:id="@+id/addresspre"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="text"
                android:hint="所在城市"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:background="@null" />
        </LinearLayout>

    </LinearLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:layout_marginTop="20dp"
        android:text="添加"
        android:textSize="20dp"
        android:background="#FF0"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout5" />




</androidx.constraintlayout.widget.ConstraintLayout>

五、程序具体实现

1.在MainActivity.java活动类中,依次流程为,获取页面标签类、绑定跳转添加信息页面、实现搜索功能的模糊查询、初始展示数据、为ListView中每个Item绑定点击事件与长按事件。

注:以下为MainActivity.java活动类的代码,绑定事件与初始数据,分别采用了内部类、直接获取展示数据。

 获取标签类

package com.example.telephonedirectoryapplication;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.telephonedirectoryapplication.sql.PersonDB;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(MainActivity.this);
        setContentView(R.layout.activity_main);
        TextView addInformation = findViewById(R.id.addInformation);
        EditText search_name_phone = findViewById(R.id.search_name_phone);
        ImageView search = findViewById(R.id.name_phone_search);
        listView = findViewById(R.id.listView1);
    }
}

初始展示数据

PersonDB personDB = new PersonDB(MainActivity.this);
        SQLiteDatabase database = personDB.getWritableDatabase();
        ArrayList<PersonEntity> array = new ArrayList<PersonEntity>();
        Cursor cursor = database.query(
                        "table_phone_user",
                        new String[]{"id","title_Image","name","phone","email","address"},
                        null,null,null,null,null);
        if (null != cursor && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                PersonEntity person = new PersonEntity();
                person.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                person.setImgAddress(cursor.getInt(cursor.getColumnIndexOrThrow("title_Image")));
                person.setName(cursor.getString(cursor.getColumnIndexOrThrow("name")));
                person.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
                person.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
                person.setAddresspre(cursor.getString(cursor.getColumnIndexOrThrow("address")));

                array.add(person);
            }
            cursor.close();
        }
        //"id, title_Image,name,phone,email,address";
        PersonAdapter fruitAdapter = new PersonAdapter(MainActivity.this,R.layout.listview,array);
        listView.setAdapter(fruitAdapter);

 绑定跳转添加信息页面

 addInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MainActivityadd.class);
                startActivity(intent);
            }
        });

 实现搜索功能的模糊查询

search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name_phone = search_name_phone.getText().toString();
                PersonDB personDB = new PersonDB(MainActivity.this);
                ArrayList<PersonEntity> array = new ArrayList<PersonEntity>();
                SQLiteDatabase database = personDB.getWritableDatabase();
                if (name_phone.length() == 11){
                    String[] selectioinArgs = {"%"+name_phone+"%"};//注意:这里没有单引号
                    String sql = "select * from table_phone_user where phone like ? ";
                    Cursor cursor = database.rawQuery(sql,selectioinArgs);
                    if (null != cursor && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            PersonEntity person = new PersonEntity();
                            person.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                            person.setImgAddress(cursor.getInt(cursor.getColumnIndexOrThrow("title_Image")));
                            person.setName(cursor.getString(cursor.getColumnIndexOrThrow("name")));
                            person.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
                            person.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
                            person.setAddresspre(cursor.getString(cursor.getColumnIndexOrThrow("address")));
                            array.add(person);
                        }
                        cursor.close();
                    }
                }else {
                    String[] selectioinArgs = {"%"+name_phone+"%"};//注意:这里没有单引号
                    String sql = "select * from table_phone_user where name like ? ";
                    Cursor cursor = database.rawQuery(sql,selectioinArgs);
                    if (null != cursor && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {
                            PersonEntity person = new PersonEntity();
                            person.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
                            person.setImgAddress(cursor.getInt(cursor.getColumnIndexOrThrow("title_Image")));
                            person.setName(cursor.getString(cursor.getColumnIndexOrThrow("name")));
                            person.setPhone(cursor.getString(cursor.getColumnIndexOrThrow("phone")));
                            person.setEmail(cursor.getString(cursor.getColumnIndexOrThrow("email")));
                            person.setAddresspre(cursor.getString(cursor.getColumnIndexOrThrow("address")));
                            array.add(person);
                        }
                        cursor.close();
                    }
                }
                PersonAdapter fruitAdapter = new PersonAdapter(MainActivity.this,R.layout.listview,array);
                listView.setAdapter(fruitAdapter);
                database.close();
            }
        });

 为ListView中每个Item绑定点击事件与长按事件,在绑定长按事件时,返回值需填为true,如果为false时,长按后同时执行长按代码与点击事件。其中长按实现了删除信息,而单击绑定了报号事件。

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Uri uri = Uri.parse("tel:" + array.get(position).getPhone());
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(uri);
                MainActivity.this.startActivity(intent);
            }
        });
        //listView长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           final int position, long id) {
                //定义AlertDialog.Builder对象,当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PersonEntity personEntity = array.get(position);
                        PersonDB personDB = new PersonDB(MainActivity.this);
                        SQLiteDatabase database = personDB.getWritableDatabase();
                        //删除  1表名、2字段名、3占位符的数据
                        database.delete("table_phone_user","id = ? ",new String[]{personEntity.getId() + ""});



                        if(array.remove(position)!=null){
                            System.out.println("success");
                        }else {
                            System.out.println("failed");
                        }
                        fruitAdapter.notifyDataSetChanged();
                        Toast.makeText(getBaseContext(), "删除列表项", Toast.LENGTH_SHORT).show();
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return true;
            }
        });

2.在具体的使用中,你会发现多出来PersonDB.java类,不要惊慌,继续看下去,你会发现PersonDB.java类其实继承了SQLiteOpenHelper.java类,用于创建数据库信息。

以下是PersonDB.java类的具体实现:

package com.example.telephonedirectoryapplication.sql;

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

import androidx.annotation.Nullable;

public class PersonDB extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "database_phone_infromtion.dp";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "table_phone_user";
    public PersonDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableQuery = "create table " + TABLE_NAME +" (" +
                "id INTEGER primary key autoincrement, " +
                "title_Image INTEGER, " +
                "name TEXT , " +
                "phone TEXT , " +
                "email TEXT , " +
                "address TEXT )";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists " + TABLE_NAME);
        onCreate(db);
    }
}

 3.在MainActivityadd.java活动类中,依次流程为,获取页面标签类、绑定跳转返回通讯录页面、修改信息、添加信息、以及控制头像的切换功能。

注:以下为MainActivityadd.java活动类的代码,绑定事件采用了内部类的方式。

获取页面标签类

package com.example.telephonedirectoryapplication;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.telephonedirectoryapplication.sql.PersonDB;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;


public class MainActivityadd extends AppCompatActivity {

    int[] arr = {R.drawable.manyear,R.drawable.womanyear,R.drawable.manold,R.drawable.womanold};
    int index = 0;
    int id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fresco.initialize(MainActivityadd.this);
        setContentView(R.layout.activity_mainadd);

        SimpleDraweeView draweeView = (SimpleDraweeView) findViewById(R.id.xuanzhe);
        draweeView.setImageURI(Uri.parse("res://drawable/"+R.drawable.manyear));

        ImageView zuojiantou = findViewById(R.id.zuojiantou);
        ImageView youjiantou = findViewById(R.id.youjiantou);
        TextView fanhui = findViewById(R.id.fanhuitext);
        Button button1 = findViewById(R.id.button);
        EditText name1 = findViewById(R.id.name1);
        EditText phone1 = findViewById(R.id.phone1);
        EditText email1 = findViewById(R.id.em);
        EditText addresspre1 = findViewById(R.id.addresspre);
        Intent intt = getIntent();
    }
}

 绑定跳转返回通讯录页面

fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivityadd.this,MainActivity.class);
                MainActivityadd.this.startActivity(intent);
            }
        });

 控制头像的切换功能

zuojiantou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index--;
                if (index < 0){
                    index = arr.length - 1;
                }
                draweeView.setImageURI(Uri.parse("res://drawable/" + arr[index]));
            }
        });
        youjiantou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ++ index;
                if (index >= arr.length){
                    index = 0;
                }
                draweeView.setImageURI(Uri.parse("res://drawable/" + arr[index]));
            }
        });

 根据通讯录页面点击修改信息时,传来的update_user字符串来对比是否需要修改数据库中的数据,将旧数据展示在文本框中。

if ("update_user".equals(intt.getStringExtra("update_user"))){
            id = intt.getIntExtra("id",-1);
            int title_Image = intt.getIntExtra("title_Image",-1);
            String name = intt.getStringExtra("name");
            String phone = intt.getStringExtra("phone");
            String email = intt.getStringExtra("email");
            String address = intt.getStringExtra("address");
            name1.setText(name);
            phone1.setText(phone);
            email1.setText(email);
            addresspre1.setText(address);
            draweeView.setImageURI(Uri.parse("res://drawable/"+title_Image));
        }

 向数据库中添加或修改数据信息

 button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = name1.getText().toString();
                String phone = phone1.getText().toString();
                String email = email1.getText().toString();
                String addresspre = addresspre1.getText().toString();
                int imgAddress = arr[index];
                PersonDB personDB = new PersonDB(MainActivityadd.this);
                SQLiteDatabase database = personDB.getWritableDatabase();
                Cursor cursor = database.query(
                        "table_phone_user",
                        new String[]{"id","title_Image","name","phone","email","address"},
                        "id = ? ",new String[]{id + ""},null,null,null);
                if (null != cursor && cursor.getCount() > 0){
                    ContentValues values = new ContentValues();
                    values.put("title_Image", imgAddress);
                    values.put("name", name);
                    values.put("phone", phone);
                    values.put("email", email);
                    values.put("address", addresspre);
                    String selection = " id = ?  ";
                    String[] selectionArgs = {id+""};
                    int count = database.update("table_phone_user", values, selection, selectionArgs);
                    if (count > 0) {
                        System.out.println("修改成功" + count);
                    } else {
                        System.out.println("修改失败" + count);
                    }
                    Toast.makeText(MainActivityadd.this,"修改成功",Toast.LENGTH_SHORT).show();
                    name1.setText("");
                    phone1.setText("");
                    email1.setText("");
                    addresspre1.setText("");
                }else {
                    ContentValues values = new ContentValues();
                    values.put("title_Image",imgAddress);
                    values.put("name",name);
                    values.put("phone",phone);
                    values.put("email",email);
                    values.put("address",addresspre);
                    long index = database.insert("table_phone_user",null,values);
                    System.out.println("插入第" + index +"条");
                    Toast.makeText(MainActivityadd.this,"添加成功",Toast.LENGTH_SHORT).show();
                    name1.setText("");
                    phone1.setText("");
                    email1.setText("");
                    addresspre1.setText("");
                }
                database.close();



                try {
                    Thread.currentThread().sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Intent intent = new Intent(MainActivityadd.this,MainActivity.class);
                MainActivityadd.this.startActivity(intent);
            }
        });

六、总结

 本文可能描述性语言不多,如果您觉得有什么不对或者不懂的问题,请私信我。

对应有说错的地方,本人认为:有则改之无则加勉。

如有不懂的代码请联系我,详细为您解答。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值