码迷,mamicode.com
首页 > 移动开发 > 详细

Android课程---添加黑名单的练习2(课堂讲解)

时间:2016-04-17 20:44:18      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

实现黑名单的添加、修改、查询和删除,首先得有封装的3个类,便于使用

BlackNumber.java

package com.hanqi.test3;

/**
 * Created by Administrator on 2016/4/15.
 */
public class BlackNumber {
    private long id;
    private String phoneNumber;

    public BlackNumber(long id, String phoneNumber) {
        this.id = id;
        this.phoneNumber = phoneNumber;
    }

    public BlackNumber() {

    }

    public long getId() {
        return id;
    }

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

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public BlackNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    @Override
    public String toString() {
        return "BlackNumber{" +
                "id=" + id +
                ", phoneNumber=‘" + phoneNumber + ‘\‘‘ +
                ‘}‘;
    }
}

DBHelper.java

package com.hanqi.test3;

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

/**
 * Created by Administrator on 2016/4/15.
 */
public class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context) {
        super(context, "blacklist.db",null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table black_number (_id integer primary key autoincrement,phone_number varchar)");

        Log.e("TAG","onCreate");

    }

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

    }
}

BlackNumberDAO.java

package com.hanqi.test3;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

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

/**
 * Created by Administrator on 2016/4/15.
 */
public class BlackNumberDAO {

    //定义成成员变量
    private DBHelper dbHelper;

    public BlackNumberDAO(Context context)
    {
        //初始化工具类
        dbHelper = new DBHelper(context);
    }

    //
    public void insert(BlackNumber blackNumber)
    {
        //获取数据库连接
        SQLiteDatabase sd = dbHelper.getWritableDatabase();

        //要添加数据的键值对集合
        ContentValues contentValues = new ContentValues();

        contentValues.put("phone_number",blackNumber.getPhoneNumber());

        //数据添加  contentValues:集合存了键值对
        sd.insert("black_number",null,contentValues);

        //关闭数据库
        sd.close();

        Log.e("TAG","修改数据成功");
    }

    //
    public void delete(long id)
    {
        //获取数据库连接
        SQLiteDatabase sd = dbHelper.getWritableDatabase();

        //数据删除
        sd.delete("black_number","_id =?",new String[]{String.valueOf(id)});

        //关闭数据库
        sd.close();

        Log.e("TAG","删除数据成功");
    }

    //
    public void update(BlackNumber blackNumber)
    {
        //获取数据库连接
        SQLiteDatabase sd = dbHelper.getWritableDatabase();

        //要添加数据的键值对集合
        ContentValues contentValues = new ContentValues();

        contentValues.put("phone_number",blackNumber.getPhoneNumber());

        //数据修改
        sd.update("black_number",contentValues,"_id =?",new String[]{String.valueOf(blackNumber.getId())});

        //关闭数据库
        sd.close();

        Log.e("TAG","添加数据成功");
    }

    ////用List(List里面装的是实体类的实例)返回数据
    public List<BlackNumber> getAll()
    {
       List<BlackNumber> rtn = new ArrayList<BlackNumber>();
       // ArrayList:实现类  List:接口

        //获取数据库连接
        SQLiteDatabase sd = dbHelper.getWritableDatabase();

        //查询返回游标
        Cursor cursor = sd.query("black_number", null, null, null, null, null, "_id desc");

        //移动游标,获取数据
        while (cursor.moveToNext())
        {
            //构造实体类的实例,放入List
            rtn.add(new BlackNumber(cursor.getLong(0),cursor.getString(1)));
        }

        Log.e("TAG","数据数量"+cursor.getCount());


        sd.close();
        return rtn;
    }
}

下面开始写页面布局

TestActivity.java

package com.hanqi.test3;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class TestActivity1 extends ListActivity {

    private ListView lv_1;
    private List<BlackNumber> data;
    private BlackListAdapter dla;

    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test1);

        //lv_1 = (ListView)findViewById(R.id.lv_1);
        lv_1 = getListView();

        //获取数据集合
        BlackNumberDAO bd = new BlackNumberDAO(this);

        data = bd.getAll();

        dla = new BlackListAdapter();

        //设置适配器
        lv_1.setAdapter(dla);
        //设置上下文菜单的监听
        lv_1.setOnCreateContextMenuListener(this);
    }

    //上下文菜单被点击
    @Override
    public boolean onContextItemSelected(MenuItem item) {

        final BlackNumber bn = data.get(position);

        switch (item.getItemId())
        {
            case 0:  //修改

                final EditText et = new EditText(this);

                et.setInputType(InputType.TYPE_CLASS_PHONE);

                et.setText(bn.getPhoneNumber());
                //弹出对话框
                new AlertDialog.Builder(this)
                        .setTitle("修改黑名单")
                        .setView(et)
                        .setNeutralButton("取消",null)
                        .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //获取修改后的值
                                bn.setPhoneNumber(et.getText().toString());

                                //执行数据库修改操作
                                BlackNumberDAO bnd = new BlackNumberDAO(TestActivity1.this);

                                bnd.update(bn);

                                //更新集合/列表
                                //bn和data里面的对象同时指向同一个内存地址
                                //如果bn被修改了,那data里面的对象同时也能够体现出变化来
                                //这就是引用类型的特点

                                //通知刷新列表
                                dla.notifyDataSetChanged();

                                Toast.makeText(TestActivity1.this, "修改成功", Toast.LENGTH_SHORT).show();
                            }
                        })

                        .show();
                break;
            case 1:  //删除

                BlackNumberDAO bd =new BlackNumberDAO(this);

                //需要id  数据库删除
                bd.delete(bn.getId());

                //刷新界面
                data.remove(position);

                //通知刷新
                dla.notifyDataSetChanged();

                Toast.makeText(TestActivity1.this, "删除成功", Toast.LENGTH_SHORT).show();

                break;
        }
        return super.onContextItemSelected(item);
    }

    public void onCreateContextMenu(ContextMenu menu,View v,
                                    ContextMenu.ContextMenuInfo menuInfo)
    {
        super.onCreateContextMenu(menu,v,menuInfo);
        menu.add(0,0,0,"修改");
        menu.add(0,1,1,"删除");

        //获取长按的适配器信息
        AdapterView.AdapterContextMenuInfo acm = (AdapterView.AdapterContextMenuInfo) menuInfo;

        position = acm.position;
    }

    //实现列表的适配器
    class BlackListAdapter extends BaseAdapter
    {
        @Override
        public int getCount() {
            return data.size();
        }

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

        @Override
        public long getItemId(int position) {
            return data.get(position).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //position:要显示的那条记录

            //判断可复用的视图是否为空
            if (convertView == null)
            {
                //获取视图
                convertView = View.inflate(TestActivity1.this,android.R.layout.simple_list_item_1,null);
            }
            //给视图绑定数据
            TextView tv =(TextView)convertView.findViewById(android.R.id.text1);
            tv.setText(data.get(position).getPhoneNumber());

            return convertView;
        }
    }

    public void bt1_OnClick(View v)
    {
        final EditText editText = new EditText(this);

        editText.setHint("请输入电话号码");

        editText.setInputType(InputType.TYPE_CLASS_PHONE);

        //editText.setLayoutParams(new DrawerLayout.LayoutParams());

        //editText.setInputType();

        //构造自定义对话框
        new AlertDialog.Builder(this)
                .setTitle("添加黑名单")
                .setView(editText)
                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //构造实体类
                        BlackNumber blacknumber = new BlackNumber(editText.getText().toString());

                        //调用数据库操作类DAO,保存数据
                        BlackNumberDAO blackNumberDAO = new BlackNumberDAO(TestActivity1.this);

                        blackNumberDAO.insert(blacknumber);

                        //添加数据到集合的顶部
                        data.add(0,blacknumber);

                        //通知适配器刷新ListView
                        dla.notifyDataSetChanged();

                        Toast.makeText(TestActivity1.this, "数据保存成功", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNeutralButton("取消",null)
                .show();
    }
}

activity_test1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    tools:context="com.hanqi.test3.TestActivity1"
    android:orientation="vertical">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@android:id/list"></ListView>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="还没添加黑名单"
        android:gravity="center"
        android:id="@android:id/empty"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加"
        android:onClick="bt1_OnClick"/>

</LinearLayout>

思维导图总结知识点:

技术分享

效果图:

技术分享

技术分享

在没有黑名单号码时,会在界面“提示还没添加黑名单”

技术分享

长按组件可以实现删除和修改

技术分享

技术分享

 

Android课程---添加黑名单的练习2(课堂讲解)

标签:

原文地址:http://www.cnblogs.com/0927wyj/p/5401875.html

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