和Activity和生命周期的联动
下载:git clone https://android.googlesource.com/platform/frameworks/volley
下载:git clone https://github.com/greenrobot/greenDAO.git
1、使用Volley、GreenDao从服务器获取数据转换成实体
一个简单request请求,该请求返回的是一个json对象
mQueue = Volley.newRequestQueue(getApplicationContext());
mQueue.add(new JsonObjectRequest(Method.GET, url, null,
new Listener() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response : " + response.toString());
}
}, null));
mQueue.start();
现在我们需要修改让其直接返回实体对象,首先需要一个GsonRequest,来处理返回的数据,将其转换成我们所要的对象import java.io.UnsupportedEncodingException;
import java.util.Map;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class GsonRequest extends Request {
private final Gson gson = new Gson();
private final Class clazz;
private final Map headers;
private final Listener listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param url
* URL of the request to make
* @param clazz
* Relevant class object, for Gson's reflection
* @param headers
* Map of request headers
*/
public GsonRequest(String url, Class clazz, Map headers,
Listener listener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
@Override
public Map getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
继承了Request,在parseNetworkResponse方法中,我们将服务器返回的数据通过gson转换为我们指定的实体类,支持各种类型的转换,包括数组(勿使用,数据库无法存储)、List、Map、对象等,字段名必须跟返回的字段名一致,且区分大小写
现在我们有了Request,就可以直接使用了
mRequestQueue.add(new GsonRequest(url, User.class, null,
new Listener() {
public void onResponse(User response) {
//TO DO
}
}
}
现在我们直接得到实体类了,这时候可以直接使用,也可以保存到数据库
2、GreenDao的使用
GreenDao下载后有多个项目,DaoCore项目是需要导入的核心类库,DaoGenerator、DaoExampleGenerator为JAVA项目,用于生成项目使用的DAO及Bean,第一步我们使用它来生成DAO:
package de.greenrobot.daogenerator.gentest;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
import de.greenrobot.daogenerator.ToMany;
/**
* Generates entities and DAOs for the example project DaoExample.
*
* Run it as a Java application (not Android).
*
* @author Markus
*/
public class ExampleDaoGenerator
{
public static void main(String[] args) throws Exception
{
Schema schema = new Schema(3, "de.greenrobot.daoexample");
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
}
private static void addNote(Schema schema)
{
Entity note = schema.addEntity("Note");
note.addIdProperty();
note.addStringProperty("text").notNull();
note.addStringProperty("comment");
note.addDateProperty("date");
}
private static void addCustomerOrder(Schema schema)
{
Entity customer = schema.addEntity("Customer");
customer.addIdProperty();
customer.addStringProperty("name").notNull();
Entity order = schema.addEntity("Order");
order.setTableName("ORDERS"); // "ORDER" is a reserved keyword
order.addIdProperty();
Property orderDate = order.addDateProperty("date").getProperty();
Property customerId = order.addLongProperty("customerId").notNull().getProperty();
order.addToOne(customer, customerId);
ToMany customerToOrders = customer.addToMany(order, customerId);
customerToOrders.setName("orders");
customerToOrders.orderAsc(orderDate);
}
}
生成代码很简单,网上也说的很多,自己看一下就可以完成,接下来我们就需要在代码中获取Dao,可以把他放在Application中
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
OpenHelper helper = new DaoMaster.DevOpenHelper(context, dir
+ Constants.DB_NAME, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null)
daoMaster = getDaoMaster(context);
daoSession = daoMaster.newSession();
}
return daoSession;
}
现在我们该有的都有了,就可以操作数据库了
1、查询
范例1:查询是否包含某个ID
public boolean isSaved(int ID)
{
QueryBuilder qb = saveListDao.queryBuilder();
qb.where(Properties.Id.eq(ID));
qb.buildCount().count();
return qb.buildCount().count() > 0 ? true : false;
}
范例2:获取整个表的数据集合,一句代码就搞定!
public List getPhotoGallery()
{
return photoGalleryDao.loadAll();// 获取图片相册
}
范例3:通过一个字段值查找对应的另一个字段值(为简便直接使用下面方法,也许有更简单的方法,尚未尝试)
/** 通过图片id查找其目录id */
public int getTypeId(int picId)
{
QueryBuilder qb = photoGalleryDao.queryBuilder();
qb.where(Properties.Id.eq(picId));
if (qb.list().size() > 0)
{
return qb.list().get(0).getTypeId();
}
else
{
return -1;
}
}
范例4:查找所有第一姓名是“Joe”并且以lastname排序。
List joes = userDao.queryBuilder()
.where(Properties.FirstName.eq("Joe"))
.orderAsc(Properties.LastName)
.list();
2.增添/插入、修改
public void addToPhotoTable(Photo p)
{
photoDao.insert(p);
}
DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();
Note note = new Note(null, noteText, comment, new Date());
noteDao.insert(note);
photoDao.insertOrReplace(photo);
photoDao.insertInTx(photo);
3.删除:
(1)清空表格数据
/** 清空相册图片列表的数据 */
public void clearPhoto()
{
photoDao.deleteAll();
}
public void deleteCityInfo(int cityId)
{
QueryBuilder qb = cityInfoDao.queryBuilder();
DeleteQuery bd = qb.where(Properties.CityId.eq(cityId)).buildDelete();
bd.executeDeleteWithoutDetachingEntities();
}
由上可见,使用greenDAO进行数据库的增删改查时及其方便,而且性能极佳。