listview

实现代码:
在src的Java代码当中com.itheima.studentinfosystem.MainActivity
    import java.util.List;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.AlertDialog.Builder;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.RadioGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.itheima.studentinfosystem.db.dao.StudentDao;
    import com.itheima.studentinfosystem.domain.Student;

    public class MainActivity extends Activity {
        private EditText et_name;
        private RadioGroup rg_sex;
        private StudentDao dao;

        private ListView lv;

        private List<Student> students;

        private MyAdapter adapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            et_name = (EditText) findViewById(R.id.et_name);
            rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
            // 找到界面下方的listview
            lv = (ListView) findViewById(R.id.lv);
            dao = new StudentDao(this);
            refreshData();
        }

        public void save(View view) {
            String name = et_name.getText().toString().trim();
            if (TextUtils.isEmpty(name)) {
                Toast.makeText(this, "请输入学生的姓名", 0).show();
                return;
            }
            int id = rg_sex.getCheckedRadioButtonId();
            String sex = "male";
            if (id == R.id.rb_male) {
                // 男
                sex = "male";
            } else {
                // 女
                sex = "female";
            }
            // 判断是否有重复的数据
            long rowid = dao.add(name, sex);
            if (rowid != -1) {
                Toast.makeText(this, "数据添加成功,在数据库的" + rowid + "行", 0).show();
                refreshData();
            } else {
                Toast.makeText(this, "数据添加失败", 0).show();
            }
        }

        /**
         * 获取数据库的全部记录,刷新显示数据
         */
        private void refreshData() {
            students = dao.findAll();
            if (adapter == null) {
                adapter = new MyAdapter();
                lv.setAdapter(adapter);
            } else {
                // 通知数据适配器更新数据,而不是new出来新的数据适配器
                adapter.notifyDataSetChanged();
            }
        }

        private class MyAdapter extends BaseAdapter {

            @Override
            public int getCount() {// 获取一共有多少个条目
                return students.size();
            }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {
                View view = null;
                if (convertView == null) {
                    // 把一个布局xml文件转化成view对象
                    view = View.inflate(MainActivity.this, R.layout.item, null);
                } else {
                    view = convertView;
                }
                // 在view里面查找孩子控件
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
                ImageView iv_sex = (ImageView) view.findViewById(R.id.iv_sex);
                Student student = students.get(position);
                String sex = student.getSex();
                if ("male".equals(sex)) {
                    iv_sex.setImageResource(R.drawable.nan);
                } else {
                    iv_sex.setImageResource(R.drawable.nv);
                }
                tv_name.setText(student.getName());
                view.findViewById(R.id.iv_delete).setOnClickListener(
                        new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AlertDialog.Builder builder = new Builder(
                                        MainActivity.this);
                                builder.setTitle("提醒");
                                builder.setMessage("是否删除这条学生信息?");
                                builder.setPositiveButton("删除",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                Student student = students
                                                        .get(position);
                                                String name = student.getName();
                                                // 从数据库删除数据.
                                                int count = dao.delete(name);
                                                if (count > 0) {
                                                    Toast.makeText(
                                                            MainActivity.this,
                                                            "数据被删除了" + count + "个",
                                                            0).show();
                                                    // 更新ui界面.
                                                    refreshData();
                                                } else {
                                                    Toast.makeText(
                                                            MainActivity.this,
                                                            "数据删除失败", 0).show();
                                                }
                                            }
                                        });
                                builder.setNegativeButton("取消", null);
                                builder.show();
                            }
                        });
                return view;
            }

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

            @Override
            public Object getItem(int position) {
                return null;
            }
        }

    }
在src的Java代码当中com.itheima.studentinfosystem.db.StudentDBOpenHelper
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

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

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table student (_id integer primary key autoincrement,name varchar(20), sex varchar(6))");
        }

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

        }
    }
在src的Java代码当中com.itheima.studentinfosystem.db.dao.StudentDao
    import java.util.ArrayList;
    import java.util.List;

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

    import com.itheima.studentinfosystem.db.StudentDBOpenHelper;
    import com.itheima.studentinfosystem.domain.Student;

    /**
     * 学生信息数据库的dao( data access objcet)
     * 增删改查
     */
    public class StudentDao {
        private StudentDBOpenHelper helper;

        /**
         * 只有一个有参的构造方法,要求必须传入上下文
         * @param context
         */
        public StudentDao(Context context) {
            helper = new StudentDBOpenHelper(context);
        }
        /**
         * 添加一个学生
         * @param name 姓名
         * @param sex 性别,male female
         * @return result 添加到数据库的那一行, -1添加失败
         */
        public long add(String name,String sex){
            SQLiteDatabase  db = helper.getWritableDatabase();
            //db.execSQL("insert into student (name,sex) values (?,?)", new Object[]{name,sex});
            ContentValues values =new ContentValues();
            values.put("name", name);
            values.put("sex", sex);
            long result = db.insert("student", null, values); //组拼sql语句实现的.带返回值
            db.close();//释放资源
            return result;
        }

        /**
         * 删除一个学生
         * @param name 姓名
         * @return result 删除了几行 0 代表删除失败
         */
        public int delete(String name){
            SQLiteDatabase  db = helper.getWritableDatabase();
            //db.execSQL("delete from student where name=?",new Object[]{name});
            int result = db.delete("student", "name=?", new String[]{name});
            db.close();//释放资源
            return result;
        }

        /**
         * 修改一个学生的性别
         * @param name 姓名
         * @param newsex 新的性别
         * @return 更新了几行 0更新失败
         */
        public int update(String name,String newsex){
            SQLiteDatabase  db = helper.getWritableDatabase();
            //db.execSQL("update student set sex =? where name=?",new Object[]{newsex,name});
            ContentValues values = new ContentValues();
            values.put("sex", newsex);
            int result = db.update("student", values, "name=?", new String[]{name});
            db.close();//释放资源
            return result;
        }
        /**
         * 查询学生的性别
         * @param name 学生的姓名
         * @return 学生性别 null代表学生不存在
         */
        public String find(String name){
            String sex = null;
            SQLiteDatabase  db = helper.getReadableDatabase();
            //结果集 游标
            //Cursor cursor = db.rawQuery("select sex from student where name=?", new String[]{name});
            Cursor cursor = db.query("student", new String[]{"sex"}, "name=?", new String[]{name}, null, null, null);
            boolean result = cursor.moveToNext();
            if(result){
                sex = cursor.getString(0);
            }
            cursor.close();//释放资源
            db.close();
            return sex;
        }
        /**
         * 获取全部的学生信息
         * @return
         */
        public List<Student> findAll(){
            List<Student> students =new ArrayList<Student>();
            SQLiteDatabase  db = helper.getReadableDatabase();
            //Cursor cursor = db.rawQuery("select name, sex from student", null);
            Cursor cursor =  db.query("student", new String[]{"name","sex"}, null, null, null, null, null);
            while(cursor.moveToNext()){
                String name = cursor.getString(0);
                String sex = cursor.getString(1);
                Student student = new Student();
                student.setName(name);
                student.setSex(sex);
                students.add(student);
            }
            cursor.close();
            db.close();
            return students;
        }

    }
在src的Java代码当中com.itheima.studentinfosystem.domain.Student
        /**
         * 学生的业务bean
         */
        public class Student {
            private String name;
            private String sex;
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            public String getSex() {
                return sex;
            }
            public void setSex(String sex) {
                this.sex = sex;
            }
            @Override
            public String toString() {
                return "Student [name=" + name + ", sex=" + sex + "]";
            }

        }
在src的Java代码当中com.itheima.studentinfosystem.test.TestStudentDao
    import com.itheima.studentinfosystem.db.dao.StudentDao;

    import android.test.AndroidTestCase;
    import android.text.TextUtils;

    public class TestStudentDao extends AndroidTestCase {

        public void testAdd() throws Exception {
            // getContext() 获取一个模拟的上下文 供测试框架使用的.
            StudentDao dao = new StudentDao(getContext());
            for (int i = 0; i < 8000; i++) {
                dao.add("刘虎"+i, "female");
            }
        }

        public void testDelete() throws Exception {
            StudentDao dao = new StudentDao(getContext());
            dao.delete("张三");
        }

        public void testUpdate() throws Exception {
            StudentDao dao = new StudentDao(getContext());
            dao.update("张三", "female");
        }

        public void testFind() throws Exception {
            StudentDao dao = new StudentDao(getContext());
            String sex = dao.find("张三");
            if (TextUtils.isEmpty(sex)) {
                System.out.println("学生不存在");
            } else {
                System.out.println("学生的性别为:" + sex);
            }
        }
    }
在res/layout/activity_main.xml当中的代码实现
    <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:orientation="vertical"
        tools:context=".MainActivity" >

        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入学生的姓名" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="请选择学生的性别:" />

        <RadioGroup
            android:id="@+id/rg_sex"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/rb_male"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:checked="true"
                android:text="男" />

            <RadioButton
                android:id="@+id/rb_female"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="女" />
        </RadioGroup>

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="save"
            android:text="保存" />

        <ListView
            android:fastScrollEnabled="true"
            android:id="@+id/lv"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </ListView>

    </LinearLayout>
在res/layout/item.xml当中的代码实现
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/iv_sex"
            android:layout_width="35dip"
            android:layout_height="35dip"
            android:src="@drawable/nan" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dip"
            android:layout_toRightOf="@id/iv_sex"
            android:text="姓名"
            android:textColor="#88ff0000"
            android:textSize="20sp" />

        <ImageView
            android:id="@+id/iv_delete"
             android:layout_centerVertical="true"
            android:layout_width="wrap_content"
            android:layout_marginRight="10dip"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:src="@drawable/delete" />

    </RelativeLayout>
在AndroidManifest.xml当中的代码实现
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.itheima.studentinfosystem"
        android:versionCode="1"
        android:versionName="1.0" >



        <!-- 测试(包名称) -->
        <instrumentation
            android:name="android.test.InstrumentationTestRunner"
            android:targetPackage="com.itheima.studentinfosystem" >
        </instrumentation>

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <uses-library android:name="android.test.runner"/>

            <activity
                android:name="com.itheima.studentinfosystem.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READme.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 、 1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READmE.文件(md如有),本项目仅用作交流学习参考,请切勿用于商业用途。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

左绍骏

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

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

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

打赏作者

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

抵扣说明:

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

余额充值