zoukankan      html  css  js  c++  java
  • 实验8 SQLite数据库操作

    实验报告

    课程名称

    基于Android平台移动互联网开发

    实验日期

    2016.04.29

    实验项目名称

    SQLite数据库操作

    实验地点

    S3010

    实验类型

    □验证型    √设计型    □综合型

    学  时

    6

    一、           实验目的及要求(本实验所涉及并要求掌握的知识点)

    1、设计一个个人通讯录,掌握Android平台下的数据库开发,该个人通讯录主要包括联系人列表和联系人详细信息等界面。

    2、程序主界面是通讯录的目录显示手机上联系人的名称。点击联系人的姓名可以显示联系人的详细信息。在按了MEMU键之后会弹出菜单栏。

    单击菜单栏上的按钮可以添加联系人和删除联系人

    二、实验环境(本实验所使用的硬件设备和相关软件)

    (1)PC机

    (2)操作系统:Windows XP

    (3)软件: Eclipse, JDK1.6,Android SDK,ADT

    三、实验内容及步骤

    1) 确定数据库的数据结构

    2) 在res/drawable-mdpi目录下拷入程序要用的图标

    3) 定义字符串资源string.xml

    4) 开发布局文件activity_main.xml用于显示联系人列表

    5) layout目录下新建一个detail.xml,用于显示联系人详细信息

    6) 开发数据库辅助类MyOpenHelper类,新建一个MyOpenHelper.java

    7) 接下来便进入MainActivity端的开发,实现数据库增加、删除、修改记录等操作

    8) 新建一个Activity名字叫DetailActivity.java,实现联系人详细信息显示功能

    四、实验结果(本实验源程序清单及运行结果或实验结论、实验设计图)

    代码:

    MainActivity:

    public class MainActivity extends Activity {

       Button btnadd, btndel;

       Intent intent = new Intent();

       ListView listview;

       MyOpenHelper usersql;

       SQLiteDatabase userdatabases;

       ArrayList<HashMap<String, Object>> userlist;

       String[] name=new String[100];

       @Override

       protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.activity_main);

           btnadd = (Button) findViewById(R.id.add);

           btndel = (Button) findViewById(R.id.delete);

           listview = (ListView) findViewById(R.id.listView1);

           usersql = new MyOpenHelper(MainActivity.this, "user.db", null, 1);

           userdatabases = usersql.getReadableDatabase();

           userlist = new ArrayList<HashMap<String, Object>>();

           Cursor cursor = userdatabases.rawQuery("select * from userTable", null);

           cursor.moveToFirst();

           if (cursor.getCount() > 0) {

              for (int i = 0; i < cursor.getCount(); i++) {

                  HashMap<String, Object> hashmap = new HashMap<String, Object>();

                  hashmap.put("name",

                         cursor.getString(cursor.getColumnIndex("name")));

                  name[i]=cursor.getString(cursor.getColumnIndex("name"));

                  hashmap.put("phone",

                         "["+cursor.getString(cursor.getColumnIndex("phone"))+"]");

                  userlist.add(hashmap);

                  if (i < cursor.getCount()) {

                     cursor.moveToNext();

                  }

              }

              SimpleAdapter sa = new SimpleAdapter(MainActivity.this, userlist,

                     R.layout.list, new String[] { "name", "phone" }, new int[] {

                         R.id.namelist, R.id.phonelist

                     });

              listview.setAdapter(sa);

           }

           listview.setOnItemClickListener(new OnItemClickListener() {

              @Override

              public void onItemClick(AdapterView<?> parent, View view,

                     int position, long id) {

                  // TODO Auto-generated method stub

                  Intent intent=new Intent(MainActivity.this,DetailActivity.class);

                  Bundle bd=new Bundle();

                  bd.putString("name", name[position]);

             

                  intent.putExtras(bd);

                  startActivity(intent);

              }

           });

           btnadd.setOnClickListener(new OnClickListener() {

              @Override

              public void onClick(View v) {

                  // TODO Auto-generated method stub

                  intent.setClass(MainActivity.this, DetailActivity.class);

                  Bundle bd=new Bundle();

                  bd.putString("name", "");

                 

                  intent.putExtras(bd);

                  startActivity(intent);

              }

           });

           btndel.setOnClickListener(new OnClickListener() {

             

              @Override

              public void onClick(View v) {

                  // TODO Auto-generated method stub

                  intent.setClass(MainActivity.this, DeleteActivicy.class);

                  startActivity(it);

              }

           });

       }

       @Override

       public boolean onCreateOptionsMenu(Menu menu) {

           // Inflate the menu; this adds items to the action bar if it is present.

           getMenuInflater().inflate(R.menu.main, menu);

           return true;

       }

    }

    DetailActivity:

    public class DetailActivity extends Activity {

       EditText edname, edphone, edmobile, edemail, edpost, edaddr, edcomp;

       String name, phone, mobile, email, post, addr, comp;

       Button btnadd;

       MyOpenHelper usersql;

       SQLiteDatabase userdatabase;

       Bundle bd;

       String selectname;

       protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.detail);

           btnadd = (Button) findViewById(R.id.deadd);

           edname = (EditText) findViewById(R.id.edname);

           edphone = (EditText) findViewById(R.id.edphone);

           edmobile = (EditText) findViewById(R.id.edmoblie);

           edemail = (EditText) findViewById(R.id.edemail);

           edpost = (EditText) findViewById(R.id.edpost);

           edaddr = (EditText) findViewById(R.id.edaddr);

           edcomp = (EditText) findViewById(R.id.edcomp);

           usersql = new MyOpenHelper(DetailActivity.this, "user.db", null, 1);

           userdatabase = usersql.getReadableDatabase();

           bd = getIntent().getExtras();

           if (!bd.getString("name").equals("")) {

              selectname = bd.getString("name");

              Cursor cursor = userdatabase.rawQuery(

                     "select * from userTable where name=?",

                     new String[] { selectname });

              cursor.moveToFirst();

              edname.setText(cursor.getString(cursor.getColumnIndex("name")));

              edphone.setText(cursor.getString(cursor.getColumnIndex("phone")));

              edmobile.setText(cursor.getString(cursor.getColumnIndex("mobile")));

              edemail.setText(cursor.getString(cursor.getColumnIndex("email")));

              edpost.setText(cursor.getString(cursor.getColumnIndex("post")));

              edaddr.setText(cursor.getString(cursor.getColumnIndex("addr")));

              edcomp.setText(cursor.getString(cursor.getColumnIndex("comp")));

              btnadd.setText("更新");

           }

           btnadd.setOnClickListener(new OnClickListener() {

              @Override

              public void onClick(View v) {

                  // TODO Auto-generated method stub

                  name = edname.getText().toString();

                  phone = edphone.getText().toString();

                  mobile = edmobile.getText().toString();

                  email = edemail.getText().toString();

                  post = edpost.getText().toString();

                  addr = edaddr.getText().toString();

                  comp = edcomp.getText().toString();

                  if (!name.equals("") && !phone.equals("") && !mobile.equals("")

                         && !email.equals("") && !post.equals("")

                         && !addr.equals("") && !comp.equals("")) {

                     Cursor cursor = userdatabase.rawQuery(

                            "select * from userTable where name=?",

                            new String[] { name });

                     cursor.moveToFirst();

                     ContentValues cv = new ContentValues();

                     cv.put("name", name);

                     cv.put("phone", phone);

                     cv.put("mobile", mobile);

                     cv.put("email", email);

                     cv.put("post", post);

                     cv.put("addr", addr);

                     cv.put("comp", comp);

                     if (cursor.getCount() <= 0) {

                         userdatabase.insert("userTable", null, cv);

                         cv.clear();

                         Toast.makeText(DetailActivity.this, "保存" + name + "成功",

                                Toast.LENGTH_LONG).show();

                         userdatabase.delete("userTable", "name=?",

                                new String[] { selectname });

                         Intent intent= new Intent();

                         intent.setClass(DetailActivity.this, MainActivity.class);

                         startActivity(it);

                         finish();

                     } else if (cursor.getCount() == 1

                            && cursor.getString(cursor.getColumnIndex("name"))

                                   .equals(selectname)) {

                         userdatabase.update("userTable", cv, "name=?",

                                new String[] { selectname });

                         cv.clear();

                         Toast.makeText(DetailActivity.this, "更新" + name + "成功",

                                Toast.LENGTH_LONG).show();

                         Intent it = new Intent();

                         it.setClass(DetailActivity.this, MainActivity.class);

                         startActivity(it);

                         finish();

                     } else {

                         Toast.makeText(DetailActivity.this, name + "已注册",

                                Toast.LENGTH_LONG).show();

                     }

                  } else {

                     Toast.makeText(DetailActivity.this, "信息不完整",

                            Toast.LENGTH_LONG).show();

                  }

              }

           });

       }

    }

    MyOpenHelper:

    package com.example.contact;

    import android.content.Context;

    import android.database.sqlite.SQLiteDatabase;

    import android.database.sqlite.SQLiteDatabase.CursorFactory;

    import android.database.sqlite.SQLiteOpenHelper;

    public class MyOpenHelper extends SQLiteOpenHelper{

       public static final String CREAT_USER="create table userTable(id integer primary key autoincrement,name,phone,mobile,email,post,addr,comp)";

       public MyOpenHelper(Context context, String name, CursorFactory factory,

              int version) {

           super(context, name, factory, version);

           // TODO Auto-generated constructor stub

       }

       @Override

       public void onCreate(SQLiteDatabase db) {

           // TODO Auto-generated method stub

           db.execSQL(CREAT_USER);

       }

       @Override

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

           // TODO Auto-generated method stub

          

       }

    }

    string.xml:

    <?xml version="1.0" encoding="utf-8"?>

    <resources>

        <string name="app_name">contact</string>

        <string name="action_settings">Settings</string>

        <string name="title">联系人列表</string>

        <string name="tvname">姓名:  </string>

        <string name="tvphone">固定电话:</string>

        <string name="tvmoblie">移动电话:</string>

        <string name="tvemail">电子邮件:</string>

        <string name="tvpost">邮政编码:</string>

        <string name="tvaddr">通信地址:</string>

        <string name="tvcomp">公司名称:</string>

        <string name="add">添加</string>

        <string name="delete">删除</string>

        <string name="back">返回</string>

    </resources>

     

    运行结果:(截图)

     

    五、实验总结(对本实验结果进行分析,实验心得体会及改进意见)

         这次实验真的真的很难很难。数据库的操作是比想象中的难很多的,这一次所有并不是我自己的,很多我也还没有研究出来,例如,列表中的字体如何设置,如何在背景黑色显示出来等等,遇到的问题很多并不是语法的错误,而是虚拟机各种小小问题,在此上面我已经奔溃好几次,程序员不是敲代码仅仅的苦,还有死机没有保存,或者保存不成功的痛。奔溃几次我想我就应该可以习惯了。

    实验评语

     

    实验成绩

     

    指导教师签名:              年   月   日

               

  • 相关阅读:
    python中os模块中文帮助
    TypeError: string indices must be integers, not str
    ValueError: multi-byte encodings are not supported
    Codeforces Round #620 (Div. 2)E(LCA求树上两点最短距离)
    Codeforces Round #620 (Div. 2)D(LIS,构造)
    Codeforces Round #619 (Div. 2)D(模拟)
    Codeforces Round #619 (Div. 2)C(构造,容斥)
    Educational Codeforces Round 82 (Rated for Div. 2)E(DP,序列自动机)
    Educational Codeforces Round 82 (Rated for Div. 2)D(模拟)
    【PAT甲级】1114 Family Property (25分)(并查集)
  • 原文地址:https://www.cnblogs.com/zhangmm/p/5488205.html
Copyright © 2011-2022 走看看