代码改变世界

实验8 SQLite数据库操作

2016-05-13 01:55  24郑杨华  阅读(329)  评论(0编辑  收藏  举报

实验报告

课程名称

基于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:

package com.example.contact;

import java.util.ArrayList;

import java.util.HashMap;

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.Button;

import android.widget.ListView;

import android.widget.SimpleAdapter;

 

public class MainActivity extends Activity {

   Button btnadd, btndel;

   Intent it = 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

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

              Bundle bd=new Bundle();

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

             

              it.putExtras(bd);

              startActivity(it);

 

          }

       });

       btndel.setOnClickListener(new OnClickListener() {

         

          @Override

          public void onClick(View v) {

              // TODO Auto-generated method stub

              it.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:

package com.example.contact;

import android.app.Activity;

import android.content.ContentValues;

import android.content.Intent;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

 

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 it = new Intent();

                     it.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();

              }

          }

       });

   }

}

DeleteActivity:

package com.example.contact;

import java.util.ArrayList;

import java.util.HashMap;

import android.app.Activity;

import android.content.Intent;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.AdapterView.OnItemClickListener;

 

public class DeleteActivicy extends Activity {

   Button btnback;

   Intent it = new Intent();

   ListView listview;

   MyOpenHelper usersql;

   SQLiteDatabase userdatabases;

   ArrayList<HashMap<String, Object>> userlist;

   String[] name = new String[100];

   Cursor cursor;

   SimpleAdapter sa;

   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.delete);

       btnback = (Button) findViewById(R.id.back);

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

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

       userdatabases = usersql.getReadableDatabase();

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

       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();

              }

          }

          sa = new SimpleAdapter(DeleteActivicy.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

             

              userdatabases.delete("userTable", "name=?",new String[] { name[position] });

             

              list();

          }

       });

       btnback.setOnClickListener(new OnClickListener() {

         

          @Override

          public void onClick(View v) {

              // TODO Auto-generated method stub

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

              startActivity(it);

              finish();

          }

       });

 

   }

   public void list(){

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

       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();

              }

          }

          sa = new SimpleAdapter(DeleteActivicy.this, userlist,

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

                        R.id.namelist, R.id.phonelist

                 });

          listview.setAdapter(sa);

       }

   }

}

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>

    <string name="deleteuser">删除联系人?</string>

    <string name="ok">确定</string>

    <string name="cancel">取消</string>

</resources>

运行结果:(截图)

 

 

 

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

这次实验虽然有比较多的时间做,但是觉得很吃力,同时这也是最后一次实验报告,想想还是有些开心的。

参考老师给的文档觉得还不难,但是做了后发现难的那部分没有太多的代码可以参考,所以借助了同学的代码。同学的代码有很多地方值得借鉴,一个思维逻辑性是开发软件的前提,没有很好的框架计划,很难找到代码的编写方向。也正是没有真正理清思路,少了一个xml文件的内容+虚拟机频出毛病,也是很容易让人抓狂的。

首先是看懂理解代码,再思考软件执行的顺序,最后再详细写每个类的内容,个人觉得这样的考虑更能让我知道下一步是哪个方向,这样就可以有方向一步一步检查问题所在。

实验评语

 

实验成绩

 

指导教师签名:              年   月   日