作业

**XML布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mpyypm.sql.MainActivity">

<EditText
    android:id="@+id/et_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:ems="20" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="增加记录"/>

<Button
android:id="@+id/btn_delect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="onClick"
android:text="删除第一条记录" />

</LinearLayout>
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:choiceMode="singleChoice"
android:listSelector="#ffaa00"
android:layout_weight="1"
android:layout_height="0dp" />

</LinearLayout>

**JAVA代码

**mainActivity

package com.example.mpyypm.sql;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ListView studentList;
private Button btnzj;
private Button btnsc;
private EditText etname;

private MyCursorAdapter adapter;
private StudentDAO studentDao;
private Student student;
private Cursor cursor;

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

    studentList = (ListView) findViewById(R.id.list_view);
    etname=(EditText)findViewById(R.id.et_name);
    btnzj = (Button) findViewById(R.id.btn_add);
    btnzj.setOnClickListener(this);
    btnsc = (Button) findViewById(R.id.btn_delect);
    btnsc.setOnClickListener(this);

    // 创建Adapter:CursorAdpater
    studentDao = new StudentDAO(this);
    if(cursor != null) {
        adapter = new MyCursorAdapter(this, cursor);
        studentList.setAdapter(adapter);
    }


    // ListView的item点击事件
    studentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Cursor cursor = (Cursor) adapterView.getItemAtPosition(i);
            if(cursor != null) {
                cursor.moveToPosition(i);
                student = new Student();
                student.setName(cursor.getString(cursor.getColumnIndex("name")));
            }
        }
    });
}

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_add:
            String name = etname.getText().toString();
            //对必填项做非空判断
            if (TextUtils.isEmpty(name)) {
                Toast.makeText(MainActivity.this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            //将这些数据存储到数据库
            //组装name对象
            Student student = new Student(name);
            //调用nameDAO的insert()方法插入数据库
            StudentDAO studentDAO = new StudentDAO(this);
            studentDAO.insert(student);
            Cursor cursor = studentDao.selectAll();
            adapter.changeCursor(cursor);
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
            break;
        case R.id.btn_delect:
            if (studentList!= null) {
                cursor.moveToFirst();
                student = new Student();
                student.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
                studentDao.delete(student.get_id());
                studentDao = new StudentDAO(this);
                cursor = studentDao.selectAll();
                adapter = new MyCursorAdapter(this, cursor);
                studentList.setAdapter(adapter);
                Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
            }
            Toast.makeText(MainActivity.this, "记录为空", Toast.LENGTH_SHORT).show();
            break;
    }

}
}

**Student

package com.example.mpyypm.sql;

import java.io.Serializable;

/**
 * Created by mpyypm on 2017/5/15.
 */

public class Student implements Serializable {
private int _id;
private String name;
public Student(){
}
public Student(String name){
    this.name=name;
}

public int get_id() {
    return _id;
}

public void set_id(int _id) {
    this._id = _id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

**MyCursorAdapter

package com.example.mpyypm.sql;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * Created by mpyypm on 2017/5/15.
*/

public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor cursor) {
    super(context, cursor, 0);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
    return LayoutInflater.from(context).inflate(R.layout.activity_main, viewGroup, false);
}

//给item的每个主键赋值
@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView name = (TextView) view.findViewById(R.id.et_name);

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

}
}

**MyDBHelper

public class MyDBHelper extends SQLiteOpenHelper {
//student表创建语句,字段包括:关键字id,姓名name,班级classmte,年龄age
private String sql="create table student(_id integer primary key autoincrement,"
        +"name text not null ,classmate text not null,age integer)";

public MyDBHelper(Context context) {
    super(context,"studentInfo",null,1);
}
//当app中没有数据库或数据库的版本为1的时候会被调用,且调用一次

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(sql);
}
//升级数据库表,当newVersion>oldVersion,会被调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists stdent");
    onCreate(db);
}
}

**StudentDAO

package com.example.mpyypm.sql;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
* Created by mpyypm on 2017/5/15.
*/


public class StudentDAO {
private Context context;
private MyDBHelper helper;
private SQLiteDatabase db;

public StudentDAO(Context context) {
    helper = new MyDBHelper(context);
}

public void insert(Student student){
    db = helper.getWritableDatabase();

    // 第一种方法
    // 2. 生成数据集合
    ContentValues values = new ContentValues();
    values.put("name", student.getName());
    // 3. 执行语句
    db.insert("student", null, values);
}


public Cursor selectAll() {
    db = helper.getReadableDatabase();
    Cursor cursor = db.query("student",null,null,null,null,null,null);
    return cursor;
}
public void delete(int id){
    db = helper.getWritableDatabase();
    //根据数据的id号来删除数据
    db.delete("student","_id=?",new String[]{String.valueOf(id)});
}
}
posted @ 2017-05-16 17:25  mpy1611  阅读(142)  评论(0)    收藏  举报