import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private DbManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IApplication application = (IApplication) getApplication() ;
// 获取 dbManager 对象 application.daoConfig 从application 中获取
dbManager = x.getDb(application.daoConfig);
findViewById(R.id.insert).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = new News();
news.setId(2);
news.setTitle("我是标题");
news.setContent("我是内容");
try {
dbManager.save(news);
} catch (DbException e) {
e.printStackTrace();
}
}
});
findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
List<News> list = dbManager.findAll(News.class);
News news = list.get(0);
news.setTitle("------");
dbManager.update(news);
System.out.println("list = " + list.size());
} catch (DbException e) {
e.printStackTrace();
}
}
});
}
}
package com.example.muhanxi.dbutils;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
/**
* Created by muhanxi on 17/4/21.
*/
//创建一个表 指定表的名称
@Table(name = "news")
public class News {
// Column 表字段名 autoGen 表示id自动增长
@Column(name = "news_id" ,isId = true,autoGen = false)
public int id ;
@Column(name = "news_title")
public String title;
@Column(name = "news_content")
public String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
package com.example.muhanxi.dbutils;
import android.app.Application;
import org.xutils.DbManager;
import org.xutils.x;
/**
* Created by muhanxi on 17/4/21.
*/
public class IApplication extends Application {
DbManager.DaoConfig daoConfig ;
@Override
public void onCreate() {
super.onCreate();
x.Ext.init(this);
x.Ext.setDebug(BuildConfig.DEBUG);
initDB();
}
public void initDB(){
daoConfig = new DbManager.DaoConfig()
.setDbName("abc.db") //设置数据库名称
.setDbVersion(1) //数据库版本
.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
@Override
public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
// TODO: ...
// 数据库版本号发生了变化 走这个回调
}
});
}
}