实现代码:
在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>
listview
最新推荐文章于 2021-08-28 12:34:18 发布