volley + greendao + gson 을 통합 하여 안 드 로 이 드 개발 을 쉬 워 집 니 다.
17546 단어 android 오픈 소스 프레임 워 크
1、Volley Google I / O 2013 에 발 표 된 안 드 로 이 드 플랫폼 용 네트워크 통신 라 이브 러 리 는 네트워크 통신 을 더욱 빠 르 고 간단 하 며 튼튼 하 게 할 수 있 습 니 다.실제로 사용 해 보 니 정말 기분 이 좋 습 니 다. 공식 적 으로 말씀 드 린 것 처럼.그 는 다음 과 같은 편리 한 기능 을 제공 했다. JSON, 이미지 등의 비동기 다운로드; 네트워크 요청 우선 순위 처리 네트워크 요청 정렬 캐 시 다단 계 취소 요청
Activity 와 생명주기 의 연동
다운로드: git clone https://android.googlesource.com/platform/frameworks/volley
2、GreenDao 현재 안 드 로 이 드 가 자주 사용 하 는 orm 프레임 워 크 는 주로 greenDAO, OrmLite, AndrORM 이 있다.인터넷 의 각종 평 가 를 종합 하면 greenDAO 의 운행 효율 이 가장 높 고 메모리 소모 가 가장 적 으 며 성능 이 가장 좋 으 며 한 쌍 이 많 고 여러 쌍 이 많 으 며 sql 언어 와 관련 될 필요 가 없다.따라서 greenDAO 프레임 워 크 를 사용 하여 프로젝트 의 orm 프레임 워 크 를 개선 하기 로 했다.
git clonehttps://github.com/greenrobot/greenDAO.git
3、Gson 이 프레임 워 크 는 Google 에서 나 온 것 으로, annotation 없 이 실 체 를 쉽게 정렬 할 수 있 으 며, annotation 을 통 해 정렬 이 필요 한 필드 를 유연 하 게 설정 할 수 있 습 니 다.
통합
Volley 를 통 해 서버 데 이 터 를 얻 고 gson 을 통 해 json 데 이 터 를 실체 로 변환 하 며 GreenDao 를 통 해 실 체 를 sqlite 데이터베이스 에 직접 저장 하고 사용 할 때 sqlite 에서 실체 클래스 를 직접 추출 할 수 있 습 니 다.전체 프로 세 스 는 통신, 데이터 베 이 스 를 접 할 필요 가 없 으 며, 모두 실체 작업 이 며, 완전히 자바 의 프로 그래 밍 습관 입 니 다.
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();
}
(2) 대상 삭제
public void deleteCityInfo(int cityId)
{
QueryBuilder qb = cityInfoDao.queryBuilder();
DeleteQuery bd = qb.where(Properties.CityId.eq(cityId)).buildDelete();
bd.executeDeleteWithoutDetachingEntities();
}
위 에서 볼 수 있 듯 이 greenDAO 를 사용 하여 데이터 베 이 스 를 추가 삭제 하고 검사 할 때 편리 하 며 성능 이 매우 좋다.