在讲义1中讲到,在我们实际的工程中,不要每次要操作数据库都获取一个session,而是在应用开始的时候通过静态方法获取一个session,官方答疑中也是这样说的(我也不知道怎样关闭一个session)。那么怎样实现呢?怎样能使得在我们的Android应用中使得调用数据库操作更加简单呢?
首先我们创建一个GreenDapHelper类:
这里用静态方法保存着DaoMaster和DaoSession,单例模式,以后每次需要用到它们直接用getter就可以了。
然后创建DbService类:
同理,单例模式,只保存一个noteDao,同时自定义了一系列对于note表的操作(这里可以自己实现其他方法)。
NoteActivity中使用的例子:
首先我们创建一个GreenDapHelper类:
- package de.greenrobot.daoexample;
- import de.greenrobot.daoexample.DaoMaster.OpenHelper;
- import android.app.Application;
- import android.content.Context;
- public class GreenDaoHelper extends Application {
- public static final String DB_NAME = "daoexample_db";
- private static GreenDaoHelper mInstance;
- private static DaoMaster daoMaster;
- private static DaoSession daoSession;
- @Override
- public void onCreate() {
- super.onCreate();
- if(mInstance == null)
- mInstance = this;
- }
- /**
- * return DaoMaster
- *
- * @param context
- */
- public static DaoMaster getDaoMaster(Context context) {
- if (daoMaster == null) {
- OpenHelper helper = new DaoMaster.DevOpenHelper(context,DB_NAME, null);
- daoMaster = new DaoMaster(helper.getWritableDatabase());
- }
- return daoMaster;
- }
- /**
- * return DaoSession
- *
- * @param context
- */
- public static DaoSession getDaoSession(Context context) {
- if (daoSession == null) {
- if (daoMaster == null) {
- daoMaster = getDaoMaster(context);
- }
- daoSession = daoMaster.newSession();
- }
- return daoSession;
- }
- }
然后创建DbService类:
- package de.greenrobot.daoexample;
- import java.util.List;
- import android.content.Context;
- public class DbService {
- private static DbService instance;
- private static Context appContext;
- private DaoSession mDaoSession;
- private NoteDao noteDao;
- public static DbService getInstance(Context context) {
- if (instance == null) {
- instance = new DbService();
- if (appContext == null){
- appContext = context.getApplicationContext();
- }
- instance.mDaoSession = GreenDaoHelper.getDaoSession(context);
- instance.noteDao = instance.mDaoSession.getNoteDao();
- }
- return instance;
- }
- public Note loadNote(long id) {
- return noteDao.load(id);
- }
- public List<Note> loadAllNote(){
- return noteDao.loadAll();
- }
- public List<Note> queryNote(String where, String... params){
- return noteDao.queryRaw(where, params);
- }
- public long saveNote(Note note){
- return noteDao.insertOrReplace(note);
- }
- public void saveNoteLists(final List<Note> list){
- if(list == null || list.isEmpty()){
- return;
- }
- noteDao.getSession().runInTx(new Runnable() {
- @Override
- public void run() {
- for(int i=0; i<list.size(); i++){
- Note note = list.get(i);
- noteDao.insertOrReplace(note);
- }
- }
- });
- }
- public void deleteAllNote(){
- noteDao.deleteAll();
- }
- public void deleteNote(long id){
- noteDao.deleteByKey(id);
- }
- public void deleteNote(Note note){
- noteDao.delete(note);
- }
- }
NoteActivity中使用的例子:
- /*
- * Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package de.greenrobot.daoexample;
- import java.text.DateFormat;
- import java.util.Date;
- import java.util.List;
- import android.app.ListActivity;
- import android.os.Bundle;
- import android.text.Editable;
- import android.text.TextWatcher;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.ArrayAdapter;
- import android.widget.EditText;
- import android.widget.ListView;
- import android.widget.TextView;
- import android.widget.TextView.OnEditorActionListener;
- public class NoteActivity extends ListActivity {
- private EditText editText;
- private long[] idArray;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- editText = (EditText) findViewById(R.id.editTextNote);
- editText.setOnEditorActionListener(new OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
- if (actionId == EditorInfo.IME_ACTION_DONE) {
- addNote();
- return true;
- }
- return false;
- }
- });
- final View button = findViewById(R.id.buttonAdd);
- button.setEnabled(false);
- editText.addTextChangedListener(new TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- boolean enable = s.length() != 0;
- button.setEnabled(enable);
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- // TODO Auto-generated method stub
- addNote();
- }
- });
- updateData();
- }
- private void updateData() {
- List<Note>noteList = DbService.getInstance(NoteActivity.this).loadAllNote();
- Note note = null;
- int size = noteList.size();
- String[] strArray = new String[size];
- idArray = new long[size];
- for (int i= 0;i<size;++i){
- note = noteList.get(i);
- strArray[size-i-1] = note.getText() + "\n" + note.getComment();
- idArray[size-i-1] = note.getId();
- }
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(NoteActivity.this, android.R.layout.simple_list_item_1, strArray);
- setListAdapter(adapter);
- }
- private void addNote() {
- String noteText = editText.getText().toString();
- editText.setText("");
- final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
- String comment = "Added on " + df.format(new Date());
- Note note = new Note(null, noteText, comment, new Date());
- DbService.getInstance(NoteActivity.this).saveNote(note);
- Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
- updateData();
- }
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- DbService.getInstance(NoteActivity.this).deleteNote(idArray[(int) id]);
- Log.d("DaoExample", "Deleted note, ID: " + idArray[(int) id]);
- updateData();
- }
- }
记得把背景色换一下哦,不然就一片黑了。
例子下载地址:http://download.csdn.net/detail/jasison/7672037
里面有freemarker.jar,greendao-generator-1.3.1.jar,greendao-1.3.7.jar