GreenDao讲义2 - 带你创建Android应用中的DbService

来源:互联网 发布:淘宝怎样能排名靠前 编辑:程序博客网 时间:2024/06/08 11:27
在讲义1中讲到,在我们实际的工程中,不要每次要操作数据库都获取一个session,而是在应用开始的时候通过静态方法获取一个session,官方答疑中也是这样说的(我也不知道怎样关闭一个session)。那么怎样实现呢?怎样能使得在我们的Android应用中使得调用数据库操作更加简单呢?
首先我们创建一个GreenDapHelper类:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package de.greenrobot.daoexample;  
  2.   
  3.   
  4. import de.greenrobot.daoexample.DaoMaster.OpenHelper;  
  5. import android.app.Application;  
  6. import android.content.Context;  
  7.   
  8.   
  9. public class GreenDaoHelper extends Application {  
  10.     public static final String DB_NAME = "daoexample_db";   
  11.     private static GreenDaoHelper mInstance;  
  12.     private static DaoMaster daoMaster;  
  13.     private static DaoSession daoSession;  
  14.   
  15.   
  16.     @Override  
  17.     public void onCreate() {  
  18.         super.onCreate();  
  19.         if(mInstance == null)  
  20.             mInstance = this;  
  21.     }  
  22.   
  23.   
  24.     /** 
  25.      * return DaoMaster 
  26.      *  
  27.      * @param context 
  28.      */  
  29.     public static DaoMaster getDaoMaster(Context context) {  
  30.         if (daoMaster == null) {  
  31.             OpenHelper helper = new DaoMaster.DevOpenHelper(context,DB_NAME, null);  
  32.             daoMaster = new DaoMaster(helper.getWritableDatabase());  
  33.         }  
  34.         return daoMaster;  
  35.     }  
  36.   
  37.   
  38.     /** 
  39.      * return DaoSession 
  40.      *  
  41.      * @param context 
  42.      */  
  43.     public static DaoSession getDaoSession(Context context) {  
  44.         if (daoSession == null) {  
  45.             if (daoMaster == null) {  
  46.                 daoMaster = getDaoMaster(context);  
  47.             }  
  48.             daoSession = daoMaster.newSession();  
  49.         }  
  50.         return daoSession;  
  51.     }  
  52. }  
这里用静态方法保存着DaoMaster和DaoSession,单例模式,以后每次需要用到它们直接用getter就可以了。
然后创建DbService类:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package de.greenrobot.daoexample;  
  2.   
  3.   
  4. import java.util.List;  
  5.   
  6.   
  7. import android.content.Context;  
  8.   
  9.   
  10. public class DbService {  
  11.     private static DbService instance;  
  12.     private static Context appContext;  
  13.     private DaoSession mDaoSession;  
  14.     private NoteDao noteDao;  
  15.   
  16.   
  17.     public static DbService getInstance(Context context) {  
  18.         if (instance == null) {  
  19.             instance = new DbService();  
  20.             if (appContext == null){  
  21.                 appContext = context.getApplicationContext();  
  22.             }  
  23.             instance.mDaoSession = GreenDaoHelper.getDaoSession(context);  
  24.             instance.noteDao = instance.mDaoSession.getNoteDao();  
  25.         }  
  26.         return instance;  
  27.     }  
  28.   
  29.   
  30.     public Note loadNote(long id) {  
  31.         return noteDao.load(id);  
  32.     }  
  33.   
  34.   
  35.     public List<Note> loadAllNote(){  
  36.         return noteDao.loadAll();  
  37.     }  
  38.   
  39.   
  40.     public List<Note> queryNote(String where, String... params){  
  41.         return noteDao.queryRaw(where, params);  
  42.     }  
  43.   
  44.   
  45.     public long saveNote(Note note){  
  46.         return noteDao.insertOrReplace(note);  
  47.     }  
  48.   
  49.   
  50.     public void saveNoteLists(final List<Note> list){  
  51.         if(list == null || list.isEmpty()){  
  52.             return;  
  53.         }  
  54.         noteDao.getSession().runInTx(new Runnable() {  
  55.             @Override  
  56.             public void run() {  
  57.                 for(int i=0; i<list.size(); i++){  
  58.                     Note note = list.get(i);  
  59.                     noteDao.insertOrReplace(note);  
  60.                 }  
  61.             }  
  62.         });  
  63.   
  64.   
  65.     }  
  66.   
  67.   
  68.     public void deleteAllNote(){  
  69.         noteDao.deleteAll();  
  70.     }  
  71.   
  72.   
  73.     public void deleteNote(long id){  
  74.         noteDao.deleteByKey(id);  
  75.     }  
  76.   
  77.   
  78.     public void deleteNote(Note note){  
  79.         noteDao.delete(note);  
  80.     }  
  81. }  
同理,单例模式,只保存一个noteDao,同时自定义了一系列对于note表的操作(这里可以自己实现其他方法)。
NoteActivity中使用的例子:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * Copyright (C) 2011 Markus Junginger, greenrobot (http://greenrobot.de) 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. package de.greenrobot.daoexample;  
  17.   
  18.   
  19. import java.text.DateFormat;  
  20. import java.util.Date;  
  21. import java.util.List;  
  22.   
  23.   
  24. import android.app.ListActivity;  
  25. import android.os.Bundle;  
  26. import android.text.Editable;  
  27. import android.text.TextWatcher;  
  28. import android.util.Log;  
  29. import android.view.KeyEvent;  
  30. import android.view.View;  
  31. import android.view.View.OnClickListener;  
  32. import android.view.inputmethod.EditorInfo;  
  33. import android.widget.ArrayAdapter;  
  34. import android.widget.EditText;  
  35. import android.widget.ListView;  
  36. import android.widget.TextView;  
  37. import android.widget.TextView.OnEditorActionListener;  
  38.   
  39.   
  40. public class NoteActivity extends ListActivity {  
  41.     private EditText editText;  
  42.     private long[] idArray;  
  43.   
  44.   
  45.     @Override  
  46.     public void onCreate(Bundle savedInstanceState) {  
  47.         super.onCreate(savedInstanceState);  
  48.         setContentView(R.layout.main);  
  49.   
  50.   
  51.         editText = (EditText) findViewById(R.id.editTextNote);  
  52.         editText.setOnEditorActionListener(new OnEditorActionListener() {  
  53.   
  54.   
  55.             @Override  
  56.             public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
  57.                 if (actionId == EditorInfo.IME_ACTION_DONE) {  
  58.                     addNote();  
  59.                     return true;  
  60.                 }  
  61.                 return false;  
  62.             }  
  63.         });  
  64.   
  65.   
  66.         final View button = findViewById(R.id.buttonAdd);  
  67.         button.setEnabled(false);  
  68.         editText.addTextChangedListener(new TextWatcher() {  
  69.   
  70.   
  71.             @Override  
  72.             public void onTextChanged(CharSequence s, int start, int before, int count) {  
  73.                 boolean enable = s.length() != 0;  
  74.                 button.setEnabled(enable);  
  75.             }  
  76.   
  77.   
  78.             @Override  
  79.             public void beforeTextChanged(CharSequence s, int start, int count, int after) {  
  80.             }  
  81.   
  82.   
  83.             @Override  
  84.             public void afterTextChanged(Editable s) {  
  85.             }  
  86.         });  
  87.         button.setOnClickListener(new OnClickListener() {  
  88.   
  89.   
  90.             @Override  
  91.             public void onClick(View arg0) {  
  92.                 // TODO Auto-generated method stub  
  93.                 addNote();  
  94.             }  
  95.               
  96.         });  
  97.         updateData();  
  98.     }  
  99.       
  100.     private void updateData() {  
  101.         List<Note>noteList = DbService.getInstance(NoteActivity.this).loadAllNote();  
  102.         Note note = null;  
  103.         int size = noteList.size();  
  104.         String[] strArray = new String[size];  
  105.         idArray = new long[size];  
  106.         for (int i= 0;i<size;++i){  
  107.             note = noteList.get(i);  
  108.             strArray[size-i-1] = note.getText() + "\n" + note.getComment();  
  109.             idArray[size-i-1] = note.getId();  
  110.         }  
  111.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(NoteActivity.this, android.R.layout.simple_list_item_1, strArray);  
  112.         setListAdapter(adapter);  
  113.     }  
  114.   
  115.   
  116.     private void addNote() {  
  117.         String noteText = editText.getText().toString();  
  118.         editText.setText("");  
  119.         final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);  
  120.         String comment = "Added on " + df.format(new Date());  
  121.         Note note = new Note(null, noteText, comment, new Date());  
  122.         DbService.getInstance(NoteActivity.this).saveNote(note);  
  123.         Log.d("DaoExample""Inserted new note, ID: " + note.getId());  
  124.         updateData();  
  125.     }  
  126.   
  127.   
  128.     @Override  
  129.     protected void onListItemClick(ListView l, View v, int position, long id) {  
  130.         DbService.getInstance(NoteActivity.this).deleteNote(idArray[(int) id]);  
  131.         Log.d("DaoExample""Deleted note, ID: " + idArray[(int) id]);  
  132.         updateData();  
  133.     }  
  134.   
  135.   
  136. }  

记得把背景色换一下哦,不然就一片黑了。


例子下载地址:http://download.csdn.net/detail/jasison/7672037

里面有freemarker.jar,greendao-generator-1.3.1.jar,greendao-1.3.7.jar


0 0
原创粉丝点击