編輯:關於Android編程
總感覺用原始的SQLLiteHelper操作數據庫有點麻煩,上網找了些android數據庫orm框架,對比了一下,現在使用ormlite的人貌似挺多的,在網上找了ormlite官方文檔,根據官方文檔,今天寫了個demo,主要是用戶注冊,用戶信息查看以及刪除,運行效果如圖:以前也用過一個同樣的orm框架Afinal,但是感覺Afinal沒有ormlite之強大。

<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+T3JtbGl0ZbnZzfijumh0dHA6Ly9vcm1saXRlLmNvbS8gICAgIL+qt6LOxLW1z8LU2KOocGRmo6mhowogtavKx8rH06LOxM7EtbXFtqOssrvSqtK7v7S1vcrH06LOxLXEvs26psXCwcujrMbkyrXA78PmtaW0yrHIvc+88rWlo6zE3Lm7v7S1w7autcSjrLbgv7S/tNOizsTOxLW1u7nKx82m09Cw79b6tcShozwvcD4KPHA+PC9wPgo8cD7Su6O60qrKudPDb3JtbGl0ZbrcvPK1paOs1rvQ6NKqz8LU2M/g06a1xMG9uPZqYXKw/KOoxL/HsNfu0MK1xGphcrD8b3JtbGl0ZS1hbmRyb2lkLTQuNDguamFyo6xvcm1saXRlLWNvcmUtNC40OC5qYXLPwtTYo6myorW8yOu5pLPMvLS/yaGjPC9wPgo8cD48L3A+CjxwPjwvcD4KPHA+tv6jurS0vajKtczlwOA8cHJlIGNsYXNzPQ=="brush:java;">@DatabaseTable(tableName = "tb_user") //如果沒有特別指出tableName = "tb_user",那麼默認情況將類名作為表名 //這裡也可以使用注解@Entity,因為ORMLite既支持它自己的注解(@DatabaseTable和 @DatabaseField)也支持很多來自javax.persistence包中標准的注解。 //你可以使用來自javax.persistence包的更多的標准JPA注解。 public class User { //用戶編號 /** * id:這個字段是否為主鍵,默認為false * generatedId:字段是否自動增加。默認為false。 * 注意:id和generatedId只能指明一個,否則會報錯的 */ //可以用javax.persistence注解: @Id,@Column @DatabaseField(generatedId=true) private int userId; //用戶名 @DatabaseField private String userName; //密碼 @DatabaseField private String password; public User() { //必須提供無參構造函數,這樣查詢的時候可以返回查詢出來的對象 } public User( int userId,String userName, String password) { this.userId = userId; this.userName = userName; this.password = password; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
三:創建SQLLiteOpenHelper,在這裡有兩個比較重要的類OrmLiteSqliteOpenHelper(當你的應用被加載時創建和更新數據庫以及為其他的類提供DAO類,必須實現onCreate(SQLiteDatabasesqliteDatabase, ConnectionSource
connectionSource) and onUpgrade(SQLiteDatabasedatabase, ConnectionSource
connectionSource, intoldVersion, int newVersion).這兩個類),RuntimeExceptionDao(默認情況下,大多數的dao方法都會拋出SQLException,因為SQLException是大部分jdbc以及其他的sql調用時拋出的默認異常。 但是在android平台上,尤其是,絕大部分的異常繼承了RuntimeException,添加了一個RuntimeExceptionDao來封裝所有在運行時因調用底層dao方法所拋出的運行時異常。)
public class DatabaseHelper extends OrmLiteSqliteOpenHelper{
// 數據庫名稱
private static final String DATABASE_NAME = "helloAndroid.db";
// 數據庫version
private static final int DATABASE_VERSION = 1;
/**
* 包含兩個泛型:
* 第一個泛型表DAO操作的類
* 第二個表示操作類的主鍵類型
*/
private Dao userDao = null;
private RuntimeExceptionDao simpleRuntimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* 插入一條數據
*/
public void insert(User user){
RuntimeExceptionDao dao = getSimpleDataDao();
//通過實體對象創建在數據庫中創建一條數據,成功返回1,說明插入了一條數據
Log.i("test", "dao = " + dao+" user= "+user);
int returnValue = dao.create(user);
Log.i("test", "插入數據後返回值:"+returnValue);
}
/**
* 查詢所有的用戶信息
* @return
*/
public List findAllUser(){
RuntimeExceptionDao dao = getSimpleDataDao();
return dao.queryForAll();
}
/**
* 刪除第一條用戶信息
*/
public void deleteById(){
RuntimeExceptionDao dao = getSimpleDataDao();
List list = dao.queryForAll();
//刪除成功返回1(刪除了一條數據)
if(list.size()>0){
int returnValue = dao.deleteById(list.get(0).getUserId());
Log.i("test", "刪除一條數據後返回值:"+returnValue);
}
}
/**
* 批量刪除用戶信息
*/
public void deleteByIds(){
RuntimeExceptionDao dao = getSimpleDataDao();
List list = dao.queryForAll();
List ids = new ArrayList();
if(list.size()>0){
for(User u:list){
ids.add(u.getUserId());
}
//返回刪除的記錄數
int returnValue = dao.deleteIds(ids);
Log.i("test", "批量刪除後返回值:"+returnValue);
}
}
public RuntimeExceptionDao getSimpleDataDao() {
if (simpleRuntimeDao == null) {
simpleRuntimeDao = getRuntimeExceptionDao(User.class);
}
Log.i("test", "simpleRuntimeDao ======= "+simpleRuntimeDao);
return simpleRuntimeDao;
}
/**
* 這個方法在你的應用升級以及它有一個更高的版本號時調用。所以需要你調整各種數據來適應新的版本
*/
@Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion,
int newVersion) {
Log.i("test", "更新....");
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
//刪掉舊版本的數據
TableUtils.dropTable(connectionSource, User.class, true);
//創建一個新的版本
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
public Dao getDao() throws SQLException {
if (userDao == null) {
userDao = getDao(User.class);
}
return userDao;
}
}
四:接下來就是Activity了。
MainActivity:當程序運行便進入該類,主要是顯示頁面的那幾個按鈕以及顯示查詢出來的用戶信息。
public class MainActivity extends Activity {
Button button1;//注冊按鈕
Button button2;//顯示按鈕
Button button3;//刪除按鈕
Button button4;//批量刪除按鈕
TextView textView;//用來顯示查詢到的用戶信息
DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)this.findViewById(R.id.main_btn_regist);
button2 = (Button)this.findViewById(R.id.main_btn_show);
button3 = (Button)this.findViewById(R.id.main_btn_delete);
button4 = (Button)this.findViewById(R.id.main_btn_deleteAll);
textView = (TextView)this.findViewById(R.id.main_show_user);
//點擊注冊按鈕跳轉到注冊頁面
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, RegistActivity.class);
startActivity(intent);
}
});
//點擊“顯示”按鈕跳轉到用戶信息顯示頁面並將注冊用戶信息顯示出來
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
List userList = helper.findAllUser();
String str = "";
if(userList.size()>0){
//將查詢到的用戶信息顯示出來
for(User user:userList){
str+="用戶"+user.getUserId()+":"+user.getUserName()+" 密碼:"+user.getPassword();
}
textView.setText(str);
}else{
textView.setText("親!還沒注冊吧!");
}
}
});
//刪除一條記錄
button3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
helper.deleteById();
}
});
//批量刪除
button4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
helper.deleteByIds();
}
});
}
@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;
}
}
對應的布局文件:main.xml
RegistActivity:用戶注冊類
/**
* 用戶注冊
* @author leox
*
*/
public class RegistActivity extends Activity {
EditText userNameEdit;//用戶名編輯框
EditText passwordEdit;//密碼編輯框
Button reButton;//注冊按鈕
DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userNameEdit = (EditText)this.findViewById(R.id.et_username);
passwordEdit = (EditText)this.findViewById(R.id.et_password);
reButton = (Button)this.findViewById(R.id.btn_regist);
reButton.setOnClickListener(new myClickListener());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class myClickListener implements OnClickListener{
@Override
public void onClick(View v) {
//用戶名
String userName = userNameEdit.getText().toString();
//密碼
String password = passwordEdit.getText().toString();
User user = new User();
user.setUserName(userName);
user.setPassword(password);
//插入注冊用戶信息
helper.insert(user);
Intent intent = new Intent();
intent.setClass(RegistActivity.this, MainActivity.class);
startActivity(intent);
}
}
}
對應的布局文件:activity_main.xml
淺談Android自定義鎖屏頁
一、為什麼需要自定義鎖屏頁鎖屏作為一種黑白屏時代就存在的手機功能,至今仍發揮著巨大作用,特別是觸屏時代的到來,鎖屏的功用被發揮到了極致。多少人曾經在無聊的時候每隔幾分鐘劃
Android7.0 PowerManagerService(2) WakeLock的使用及流程
作為移動終端,電量是一種稀缺資源,需要盡可能的節省。於是,Android系統在空閒時,會主動進入到休眠狀態。我們知道整個Android系統中運行著很多個進程,因此必須有一
Android自定義控件仿QQ編輯和選取圓形頭像
android大家都有很多需要用戶上傳頭像的需求,有的是選方形,有的是圓角矩形,有的是圓形。首先我們要做一個處理圖片的自定義控件,把傳入的圖片,經過用戶選擇區域,處理成一
計算器(android)
對計算器的一些說明: 此計算器比較簡陋,可以實現加減乘除這些運算,並能實現連續運算。對小數運算進行了優化了,避免了小數在計算時出現誤差。 主界面: calculato