1.创建数据库
首先,我们需要一个类来继承Android提供的SQLiteOpenHelper类,它提供了一系列逻辑以帮助我们规范的创建和升级数据库,为此,我们需要至少实现以下三种方法。
构造函数 :这需要Context(上下文),数据库名称,可选的游标工厂和数据库版本号。
onCreate(SQLiteDatabase db): 初次创建数据库是调用的方法
onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) :当我们需要的架构版本与数据库的架构版本不匹配时,将调用此方法,它会向我们传递一个SQLiteDatabase对象以及新旧版本号。 因此,我们可以更新数据库。
示例:
public class DatabaseHelper extends SQLiteOpenHelper {
// 表名
public static final String TABLE_NAME = "testTable.db";
// 列名
public static final String _ID = "_id";
public static final String SUBJECT = "subject";
public static final String DESC = "description";
// 数据库名称
static final String DB_NAME = "TEST.DB";
// 数据库版本号,一般初始值设为1
static final int DB_VERSION = 1;
// 创建表的语句
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT + " TEXT NOT NULL, " +
DESC + " TEXT);";
/**
* 方法说明:构造器
* 参数说明:
* Context(例如Activity),
* 数据库名称,
* 可选的游标工厂(我们将在后面讨论)
* 数据库版本(通常从1开始)然后再增加
*/
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* 方法说明:初次创建数据库调用的方法
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE); //创建一个表
}
/**
* 方法说明:数据库更新时调用的方法
* 注意这样是不合规的,因为这样会把原本数据库的数据删除,这里只用作演示
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//DROP TABLE IF EXISTS 代表如果存在那么就删除这个表
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db); // 重新创建一个表,
}
}
?这里,我们定义了数据库名称为TEST.DB,表名testTable,并且testTable中有三个字段,分别是_id,subject,description 。
这时数据库还没有被创建,要等到调用getWritableDatabase()后才开始创建
?2.执行数据库的CRUD(创建,读取,更新和删除)操作
然后我们定义一个DBManager 类来执行所有的数据库的CRUD(创建,读取,更新和删除)操作
示例:
public class DBManager {
private DatabaseHelper dbHelper;
private final Context context;
private SQLiteDatabase database;
//用来接收上下文
public DBManager(Context c) {
context = c;
}
/**
* 方法说明:打开和关闭Android SQLite数据库连接
* 在执行任何数据库操作(如插入,更新,删除表中的记录)之前,首先通过
* getWritableDatabase()方法打开数据库连接
*/
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
/**
* 方法说明:关闭数据库连接
*/
public void close() {
dbHelper.close();
}
/**
* 方法说明:将新记录插入Android SQLite数据库表
*/
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
/**
* 方法说明:查询的整个结果集
*/
public Cursor fetch() {
String[] columns = new String[] { DatabaseHelper._ID, DatabaseHelper.SUBJECT,
DatabaseHelper.DESC };
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null,
null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
/**
* 方法说明:更新Android SQLite数据库表中的记录
*/
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i;
i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
return i;
}
/**
* 方法说明:Android SQLite –删除记录
*/
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
3.添加数据
新建一个Activity,我将它命名为ModifyCountryActivity,这里的布局很简单,两个EditText,在加一个Button
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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.AddCountryActivity">
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_title"
tools:ignore="Autofill,TextFields">
<requestFocus />
</EditText>
<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5"
tools:ignore="Autofill" />
<Button
android:id="@+id/add_record"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/add_record" />
</LinearLayout>
业务逻辑示例代码
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText subjectEditText;
private EditText descEditText;
private DBManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_country);
subjectEditText = findViewById(R.id.subject_edittext);
descEditText = findViewById(R.id.description_edittext);
Button addTodoBtn = findViewById(R.id.add_record);
dbManager = new DBManager(this);
dbManager.open();
addTodoBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.add_record) {
final String name = subjectEditText.getText().toString();
final String desc = descEditText.getText().toString();
dbManager.insert(name, desc);//往数据库中添加数据
Intent main = new Intent(AddCountryActivity.this, MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
}
}
}
4.修改和删除
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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.ModifyCountryActivity">
<EditText
android:id="@+id/subject_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/enter_title" />
<EditText
android:id="@+id/description_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/enter_desc"
android:inputType="textMultiLine"
android:minLines="5"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_update" />
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/btn_delete" />
</LinearLayout>
</LinearLayout>
业务逻辑示例代码
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText titleText;
private EditText descText;
private long _id;
private DBManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_country);
dbManager = new DBManager(this);
dbManager.open();
titleText = (EditText) findViewById(R.id.subject_edittext);
descText = (EditText) findViewById(R.id.description_edittext);
Button updateBtn = (Button) findViewById(R.id.btn_update);
Button deleteBtn = (Button) findViewById(R.id.btn_delete);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String name = intent.getStringExtra("title");
String desc = intent.getStringExtra("desc");
_id = Long.parseLong(id);
titleText.setText(name);
descText.setText(desc);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
String title = titleText.getText().toString();
String desc = descText.getText().toString();
dbManager.update(_id, title, desc);
this.returnHome();
break;
case R.id.btn_delete:
dbManager.delete(_id);
this.returnHome();
break;
}
}
public void returnHome() {
Intent home_intent = new Intent(getApplicationContext(), MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
5.MainActivity
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="match_parent">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:padding="10dp" >
</ListView>
<!--提示视图-->
<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/empty_list_text" />
</RelativeLayout>
业务逻辑
public class MainActivity extends AppCompatActivity {
final String[] from = new String[]{DatabaseHelper._ID,
DatabaseHelper.SUBJECT, DatabaseHelper.DESC};
final int[] to = new int[]{R.id.id, R.id.title, R.id.desc};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBManager dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
ListView listView = (ListView) findViewById(R.id.list_view);
// 提示视图,在ListView数据为空或者Adapter为空的时候显示
listView.setEmptyView(findViewById(R.id.empty));
// 用SimpleCursorAdapter来绑定数据库里面的数据
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
// 为Listview设置适配器
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_record) {
Intent add_mem = new Intent(this, AddCountryActivity.class);
startActivity(add_mem);
}
return super.onOptionsItemSelected(item);
}
}
6.mune
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/add_record"
android:icon="@android:drawable/ic_menu_add"
android:orderInCategory="100"
android:title="@string/add_record"
app:showAsAction="always" />
</menu>
7.String
<resources>
<string name="app_name">MySQLite</string>
<string name="enter_name">国名</string>
<string name="add_record">添加记录</string>
<string name="btn_update">更新</string>
<string name="btn_delete">删除</string>
<string name="empty_list_text">没有发现任何记录</string>
<string name="enter_desc">货币</string>
<string name="enter_title">国家</string>
<string name="practice">SQLitePractice</string>
</resources>
下班了,拜拜,元旦快乐!!!
|