Android SQLite数据库CRUD示例
在本教程中,我们将了解Android SQLite数据库CRUD示例。
Android SQLite是开源关系数据库,可用于执行CRUD操作。
我们不必为此进行显式安装。
它可在Android中默认提供。
让我们从简单的例子开始:
在此示例中,我们将创建列表查看以显示Country列表,并在SQLite数据库的帮助下支持所有CRUD操作。
当我们将新的国家添加到列表或者删除任何现有国家/地区时,它将反映在数据库中。
数据库表结构:
表名称:Country
| 列名 | 数据类型 | 主键 |
|---|---|---|
| Id | Integer | Yes |
| CountryName | Text | No |
| Population | Long | No |
第1步:创建项目
创建Android应用程序项目"SQLitedatabasecrudexample"。
第2步:创建布局
更改RES - >布局 - > Activity_main.xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.theitroad.sqlitedatabasecrudexample.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Country"
android:id="@+id/btnSubmit"
<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnSubmit"
</RelativeLayout>
我们将在设计视图中看到以下屏幕。
第3步:创建国家类
创建一个Country类,该类将与SQLite数据库中的Country表对应。
package com.theitroad.sqlitedatabasecrudexample;
/*
* This is our model class and it corresponds to Country table in database
*/
import static android.R.attr.name;
public class Country{
int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
//constructor
public Country(String countryName, long population){
this.countryName = countryName;
this.population = population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
步骤4:创建SQLitedatabaseHandler以定义数据库操作。
我们将创建一个名为SqlitedatabaseHandler的类,它将扩展SQLiteopenHelper并覆盖OnCreate和OnUpdate方法。
我们还将添加一些CRUD方法。
- addcountry
- getcountry
- GetAllCountries.
- Updatecountry.
- deletecountry
- delelteallcountries
以上所有方法都将与SQLite数据库交互并执行CRUD操作。
package com.theitroad.sqlitedatabasecrudexample;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class SQLiteDatabaseHandler extends SQLiteOpenHelper {
//All Static variables
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "countryData";
//Country table name
private static final String TABLE_COUNTRY= "Country";
//Country Table Columns names
private static final String KEY_ID = "id";
private static final String COUNTRY_NAME = "CountryName";
private static final String POPULATION = "Population";
public SQLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_COUNTRY + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + COUNTRY_NAME + " TEXT,"
+ COUNTRY_NAME + " LONG" + ")";
db.execSQL(CREATE_COUNTRY_TABLE);
}
//Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTRY);
//Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
//Adding new country
void addCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_NAME, country.getCountryName()); //Country Name
values.put(POPULATION, country.getPopulation()); //Country Population
//Inserting Row
db.insert(TABLE_COUNTRY, null, values);
db.close(); //Closing database connection
}
//Getting single country
Country getCountry(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_COUNTRY, new String[] { KEY_ID,
COUNTRY_NAME, POPULATION }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Country country = new Country(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getLong(2));
//return country
return country;
}
//Getting All Countries
public List getAllCountries() {
List countryList = new ArrayList();
//Select All Query
String selectQuery = "SELECT * FROM " + TABLE_COUNTRY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(Integer.parseInt(cursor.getString(0)));
country.setCountryName(cursor.getString(1));
country.setPopulation(cursor.getLong(2));
//Adding country to list
countryList.add(country);
} while (cursor.moveToNext());
}
//return country list
return countryList;
}
//Updating single country
public int updateCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_NAME, country.getCountryName());
values.put(POPULATION, country.getPopulation());
//updating row
return db.update(TABLE_COUNTRY, values, KEY_ID + " = ?",
new String[] { String.valueOf(country.getId()) });
}
//Deleting single country
public void deleteCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_COUNTRY, KEY_ID + " = ?",
new String[] { String.valueOf(country.getId()) });
db.close();
}
//Deleting all countries
public void deleteAllCountries() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_COUNTRY,null,null);
db.close();
}
//Getting countries Count
public int getCountriesCount() {
String countQuery = "SELECT * FROM " + TABLE_COUNTRY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
//return count
return cursor.getCount();
}
}
步骤5:为行创建布局
正如我们在Activity_main.xml中声明listview小部件。
现在我们需要为单个行提供布局。
- 转到res - >布局
- 右键单击布局
- 单击"新建 - >文件"。
- 创建名为"row_item.xml"的文件,并在row_item.xml中粘贴以下代码。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="30dp"
android:textColor="#1E90FF"
android:id="@+id/textViewId"
android:layout_row="0"
android:layout_column="1"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textColor="#4B0082"
android:layout_below="@+id/textViewId"
android:id="@+id/textViewCountry"
android:layout_row="1"
android:layout_column="1"
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textColor="#4B0082"
android:layout_below="@+id/textViewCountry"
android:id="@+id/textViewPopulation"
android:layout_row="1"
android:layout_column="2"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="100dp"
android:layout_marginTop="30dp"
android:id="@+id/edit"
android:text="Edit"
android:layout_toRightOf="@+id/textViewId"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginRight="10dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="10dp"
android:id="@+id/delete"
android:text="Delete"
android:layout_toRightOf="@+id/edit"
</RelativeLayout>
步骤6:为ListView创建ArrayAdapter
在创建捕获期之前,我们需要为自定义ListView行创建CustomCountrylist类。
package com.theitroad.sqlitedatabasecrudexample;
import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomCountryList extends BaseAdapter {
private Activity context;
ArrayList countries;
private PopupWindow pwindo;
SQLiteDatabaseHandler db;
BaseAdapter ba;
public CustomCountryList(Activity context, ArrayList countries,SQLiteDatabaseHandler db) {
this.context = context;
this.countries=countries;
this.db=db;
}
public static class ViewHolder
{
TextView textViewId;
TextView textViewCountry;
TextView textViewPopulation;
Button editButton;
Button deleteButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = context.getLayoutInflater();
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
row = inflater.inflate(R.layout.row_item, null, true);
vh.textViewId = (TextView) row.findViewById(R.id.textViewId);
vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
vh.textViewPopulation = (TextView) row.findViewById(R.id.textViewPopulation);
vh.editButton = (Button) row.findViewById(R.id.edit);
vh.deleteButton = (Button) row.findViewById(R.id.delete);
//store the holder with the view.
row.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.textViewCountry.setText(countries.get(position).getCountryName());
vh.textViewId.setText("" + countries.get(position).getId());
vh.textViewPopulation.setText("" + countries.get(position).getPopulation());
final int positionPopup = position;
vh.editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Save: ", "" + positionPopup);
editPopup(positionPopup);
}
});
vh.deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Last Index", "" + positionPopup);
// Integer index = (Integer) view.getTag();
db.deleteCountry(countries.get(positionPopup));
// countries.remove(index.intValue());
countries = (ArrayList) db.getAllCountries();
Log.d("Country size", "" + countries.size());
notifyDataSetChanged();
}
});
return row;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return position;
}
public int getCount() {
return countries.size();
}
public void editPopup(final int positionPopup)
{
LayoutInflater inflater = context.getLayoutInflater();
View layout = inflater.inflate(R.layout.edit_popup,
(ViewGroup) context.findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 600, 670, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);
countryEdit.setText(countries.get(positionPopup).getCountryName());
populationEdit.setText("" + countries.get(positionPopup).getPopulation());
Log.d("Name: ", "" + countries.get(positionPopup).getPopulation());
Button save = (Button) layout.findViewById(R.id.save_popup);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String countryStr = countryEdit.getText().toString();
String population = populationEdit.getText().toString();
Country country = countries.get(positionPopup);
country.setCountryName(countryStr);
country.setPopulation(Long.parseLong(population));
db.updateCountry(country);
countries = (ArrayList) db.getAllCountries();
notifyDataSetChanged();
for (Country country1 : countries) {
String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
//Writing Countries to log
Log.d("Name: ", log);
}
pwindo.dismiss();
}
});
}
}
此类用于填充ListView的数据。
GetView方法被调用用于绘制每一行。
当我们单击编辑时,我们将看到一个弹出窗口以编辑国家/地区名称和人口。
如果单击"删除",则将从ListView和SQLite数据库中删除国家/地区。
第7步:创建MainActivity
更改src/main/packageName/mainActivity.java如下:
package com.theitroad.sqlitedatabasecrudexample;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList countries;
SQLiteDatabaseHandler db;
Button btnSubmit;
PopupWindow pwindo;
Activity activity;
ListView listView;
CustomCountryList customCountryList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;
db= new SQLiteDatabaseHandler(this);
listView = (ListView) findViewById(android.R.id.list);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addPopUp();
}
});
Log.d("MainActivity: ", "Before reading mainactivity");
countries = (ArrayList) db.getAllCountries();
for (Country country : countries) {
String log = "Id: " + country.getId() + " ,Name: " + country.getCountryName() + " ,Population: " + country.getPopulation();
//Writing Countries to log
Log.d("Name: ", log);
}
CustomCountryList customCountryList = new CustomCountryList(this, countries, db);
listView.setAdapter(customCountryList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(getApplicationContext(), "You Selected " + countries.get(position).getCountryName() + " as Country", Toast.LENGTH_SHORT).show();
}
});
}
public void addPopUp() {
LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.edit_popup,
(ViewGroup) activity.findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 600, 670, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);
Button save = (Button) layout.findViewById(R.id.save_popup);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String countryStr = countryEdit.getText().toString();
String population = populationEdit.getText().toString();
Country country = new Country(countryStr, Long.parseLong(population));
db.addCountry(country);
if(customCountryList==null)
{
customCountryList = new CustomCountryList(activity, countries, db);
listView.setAdapter(customCountryList);
}
customCountryList.countries = (ArrayList) db.getAllCountries();
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
for (Country country1 : countries) {
String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + " ,Population: " + country1.getPopulation();
//Writing Countries to log
Log.d("Name: ", log);
}
pwindo.dismiss();
}
});
}
}
当我们单击"添加国家"按钮时,我们将获得一个popup.you put国家名称和人口和国家将添加到列表中。
第8步:运行应用程序
运行应用程序时,单击"添加国家"按钮
我将国家名称放在丹麦和人口为10000。
单击"保存"时,将保存到数据库。

