0


Android Studio 简易通讯录制作 (Java)

通讯录首页:

添加联系人页面:

修改联系人:

删除联系人:

程序代码:

MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity{
    private ImageView iv_add;
    private ListView lv_show;
    private EditText et_name,et_phone;
    private MyAdapter myAdapter;
    private DBHelper dbHelper;
    private List<User> userList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_add = findViewById(R.id.iv_add);
        lv_show = findViewById(R.id.lv_show);
        if (userList != null) {
            userList.clear();
        }
        dbHelper = new DBHelper(MainActivity.this, "user.db", null, 1);
        updateListView();
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addData();
            }
        });
        lv_show.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateData(position);
            }
        });
        lv_show.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deleteData(position);
                return true;
            }
        });
    }
    private void addData() {
        AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
        View dialogView=View.inflate(MainActivity.this,R.layout.dialog,null);
        builder.setIcon(R.drawable.icon)
                .setTitle("添加联系人")
                .setView(dialogView);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                et_name=dialogView.findViewById(R.id.et_name);
                et_phone=dialogView.findViewById(R.id.et_pwd);
                String name=et_name.getText().toString();
                String phone=et_phone.getText().toString();
                if (phone.length()!=11){
                    showToast("电话号码长度不符合要求");
                }else {
                    User user=dbHelper.get(name);
                    if (user.getName()==null){
                        if (dbHelper.insert(name,phone)){
                            showToast("添加成功");
                            updateListView();
                        }else{
                            showToast("添加失败");
                        }
                    }else {
                        showToast("该联系人已存在");
                    }
                }
            }
        })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }
    private void deleteData(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.drawable.icon)
                .setTitle("提示")
                .setMessage("是否删除该联系人?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        User user = (User) myAdapter.getItem(position);
                        String deleteId = user.getId();
                        if (dbHelper.delete(deleteId)) {
                            updateListView();
                            showToast("删除成功");
                        } else {
                            showToast("删除失败");
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void updateData(int position) {
        View dialogView = View.inflate(MainActivity.this, R.layout.dialog, null);
        User user = (User) myAdapter.getItem(position);
        et_name = dialogView.findViewById(R.id.et_name);
        et_phone = dialogView.findViewById(R.id.et_pwd);
        et_name.setText(user.getName());
        et_phone.setText(user.getPhone());
        String findId = user.getId();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.drawable.icon)
                .setTitle("修改联系人")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = et_name.getText().toString();
                        String phone = et_phone.getText().toString();
                        if (phone.length()!=11){
                            showToast("电话号码长度不符合要求");
                        }else {
                            User user=dbHelper.get(name);
                            if (user.getName()==null){
                                if (dbHelper.update(findId,name,phone)){
                                    showToast("修改成功");
                                    updateListView();
                                }else{
                                    showToast("修改失败");
                                }
                            }else {
                                showToast("该联系人已存在");
                            }
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
    public void updateListView(){
        userList=dbHelper.query();
        myAdapter=new MyAdapter(userList,MainActivity.this);
        lv_show.setAdapter(myAdapter);
    }
    public void showToast(String msg){
        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
    }
}

MyAdapter.java

package com.example.myapplication;

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 java.util.List;

public class MyAdapter extends BaseAdapter {
    //使用list<Nate>,list会存储数据库中note表所有记录。
    private List<User> list;
    //用于将某个布局转换为view的对象。
    private LayoutInflater layoutInflater;
    //当创建MyAdapter对象的时候,需要list的数据
    public MyAdapter(List<User> list, Context context){
        this.list=list;
        layoutInflater=LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView==null){
            convertView=layoutInflater.inflate(R.layout.item,null,false);
            viewHolder=new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        }else {
            viewHolder=(ViewHolder)convertView.getTag();
        }
        //将数据库中的内容加载到对应的控件上
        User user =(User) getItem(position);
        viewHolder.tv_showName.setText(user.getName());
        viewHolder.tv_showPhone.setText(user.getPhone());
        return convertView;
    }
    //用于给item的视图加载数据内容。
    class ViewHolder{
        TextView tv_showName,tv_showPhone;
        public ViewHolder(View view){
            tv_showName=view.findViewById(R.id.tv_showName);
            tv_showPhone=view.findViewById(R.id.tv_showPhone);
        }
    }
}

DBHelper.java

package com.example.myapplication;

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

import androidx.annotation.Nullable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DBHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;
    ContentValues contentValues = new ContentValues();
    public DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        db=this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table user(id integer primary key autoincrement,name text,phone text)");
    }
    //添加数据
    public boolean insert(String name,String phone) {
        contentValues.put("name", name);
        contentValues.put("phone", phone);
        long result = db.insert("user", null, contentValues);
        return result > 0 ? true : false;
    }
    public boolean delete(String id){
        int result=db.delete("user","id=?",new String[]{id});
        return result>0?true:false;
    }
    //修改数据,根据id进行修改
    public boolean update(String id,String name,String phone){
        contentValues.put("id",id);
        contentValues.put("name",name);
        contentValues.put("phone",phone);
        int result=db.update("user",contentValues,"id=?",new String[]{id});
        return result>0?true:false;
    }
    //查询数据,查询表中的所有内容,将查询的内容用note的对象属性进行存储,并将该对象存入集合中。
    public List<User> query(){
        List<User> list=new ArrayList<>();
        Cursor result=db.query("user",null,null,null,
                null,null,null,null);
        if (result!=null){
            while (result.moveToNext()) {
                User user = new User();
                user.setId(String.valueOf(result.getInt(0)));
                user.setName(result.getString(1));   //1即第二列,指内容
                user.setPhone(result.getString(2));  //2即第三列,指时间
                list.add(user);
            }result.close();
        }return list;
    }

    public User get(String name) {
        User user=new User();
        Cursor result=db.query("user",null,"name=?",new String[]{name},
                null,null,null,null);
        if (result.getCount()==1){
            result.moveToFirst();
            user.setName(result.getString(1));
            user.setPhone(result.getString(2));
            return user;
        }else {
            user.setName(null);
            user.setPhone(null);
            return user;
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

User.java

package com.example.myapplication;

public class User {
    private String id;
    private String name;
    private String phone;
    public String getId() {
        return id;
    }

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

    public String getPhone() {
        return phone;
    }

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

    public String getName() {
        return name;
    }

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

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tv_title"
        android:gravity="center"
        android:textSize="25dp"
        android:textColor="@color/B_group_1"
        android:background="@color/B_group_3"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="通讯录" />

    <ListView
        android:id="@+id/lv_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/tv_title"
        android:background="@color/B_group_4"
        android:textColor="@color/B_group_1"></ListView>
    <ImageView
        android:id="@+id/iv_add"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/add"
        android:layout_margin="20dp"
        android:layout_width="50dp"
        android:layout_height="50dp">
    </ImageView>
</RelativeLayout>

dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingTop="20dp"
    android:paddingLeft="40dp"
    android:paddingRight="40dp"
    android:paddingBottom="20dp"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tv_name"
        android:text="姓名"
        android:textSize="20dp"
        android:textColor="@color/B_group_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></TextView>
    <EditText
        android:id="@+id/et_name"
        android:hint="请输入姓名"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></EditText>
    <TextView
        android:id="@+id/tv_pwd"
        android:text="电话"
        android:textSize="20dp"
        android:textColor="@color/B_group_1"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></TextView>
    <EditText
        android:id="@+id/et_pwd"
        android:hint="请输入电话"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"></EditText>
</LinearLayout>

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:padding="10dp"
    android:orientation="horizontal"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/tv_showName"
        android:textColor="@color/B_group_1"
        android:text="测试信息"
        android:layout_weight="1"
        android:textSize="20dp"
        android:layout_width="0dp"
        android:layout_height="wrap_content">
    </TextView>
    <TextView
        android:id="@+id/tv_showPhone"
        android:text="1234566"
        android:layout_weight="2"
        android:inputType="number"
        android:layout_width="0dp"
        android:layout_height="wrap_content">
    </TextView>

</LinearLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <color name="B_group_1">#0B132B</color>
    <color name="B_group_2">#A49DBE</color>
    <color name="B_group_3">#D5CFE1</color>
    <color name="B_group_4">#E9E7EF</color>
    <color name="B_group_5">#D8C4C4</color>
</resources>

详细见:https://gitee.com/love1213/Android-Studio-Contacts.git


本文转载自: https://blog.csdn.net/qq_62760217/article/details/129998547
版权归原作者 qq_62760217 所有, 如有侵权,请联系我们删除。

“Android Studio 简易通讯录制作 (Java)”的评论:

还没有评论