Android编程连接MongoDB及增删改查等基本操作示例
本文实例讲述了android编程连接mongodb及增删改查等基本操作。分享给大家供大家参考,具体如下:
mongodb简介
mongodb,分布式文档存储数据库,由c++语言编写,旨在为web应用提供可扩展的高性能数据存储解决方案。mongodb是一个高性能,开源,无模式的文档型数据库,是当前nosql数据库中比较热门的一种。它在许多场景下可用于替代传统的关系型数据库或键/值存储方式。mongo使用c++开发。
mongo安装参考
1)下载安装包文件,解压到某一文件夹下。
官方下载地址:http://www.mongodb.org/downloads
2)配置环境变量:在path后添加安装路径。
3)启动mongo数据库:
进入“cmd”->键入“mongod --dbpath d:\amp\mongodbdata”
d:\amp\mongodbdata 表示数据库文件存储路径
4)启动mongo客户端:
mongo 127.0.0.1:27017/admin
android 连接mongodb
步骤1:下载并导入jar包到工程
步骤2:安装mongodb到pc端(参见mongodb安装)
步骤3:编写代码连接mongodb实现简单操作(增删改查)
代码参考(android端,也适用于java等工程)
1. mongodbutil.java
package com.hills.happytest.utils; import java.util.list; import org.bson.types.objectid; import com.mongodb.basicdbobject; import com.mongodb.db; import com.mongodb.dbcollection; import com.mongodb.dbcursor; import com.mongodb.dbobject; import com.mongodb.mongo; /** * class name: mongodbutil.java * function: * the util that mongodb operate. * modifications: * * @author gym yung. * @datetime 2014-10-29 下午1:56:49 * @version 1.0 */ public class mongodbutil { static mongo connection = null; static db db = null; public mongodbutil(string dbname) throws exception { connection = new mongo("10.0.2.2:27017"); db = connection.getdb(dbname); } public static mongo getconnection() { return connection; } /** * create a blanket collection. * @param collname :collection name. */ public void createcollection(string collname) { dbobject dbs = new basicdbobject(); dbs.put("test", "test"); db.createcollection(collname, dbs); } /** * insert dbobject into collection. * @param dbobject * @param collname */ public void insert(dbobject dbobject,string collname) { dbcollection collection = db.getcollection(collname); collection.insert(dbobject); } /** * insert dbobject list into collection. * @param dbobjects * @param collname */ public void insertbatch(list<dbobject> dbobjects,string collname) { dbcollection collection = db.getcollection(collname); collection.insert(dbobjects); } /** * delete data by id. * @param id * @param collname * @return */ public int deletebyid(string id,string collname) { dbcollection collection = db.getcollection(collname); dbobject dbs = new basicdbobject("_id", new objectid(id)); int counts = collection.remove(dbs).getn(); return counts; } /** * delete data by condition. * @param dbobject * @param collname * @return */ public int deletebydbs(dbobject dbobject,string collname) { dbcollection collection = db.getcollection(collname); int count = collection.remove(dbobject).getn(); return count; } /** * update data. * @param find * @param update * @param upsert * @param multi * @param collname * @return */ public int update(dbobject find,dbobject update,boolean upsert,boolean multi,string collname) { dbcollection collection = db.getcollection(collname); int count = collection.update(find, update, upsert, multi).getn(); return count; } /** * find data with page. * @param ref * @param keys * @param start * @param limit * @param collname * @return */ public dbcursor findwithpage(dbobject where,dbobject selection,int start,int limit,string collname) { dbcursor cursor = findnopage(where, selection, collname); return cursor.limit(limit).skip(start); } /** * find data no page. * @param ref * @param keys * @param collname * @return */ public dbcursor findnopage(dbobject where,dbobject selection,string collname) { dbcollection collection = db.getcollection(collname); dbcursor cursor = collection.find(where, selection); return cursor; } }
2. mongodbdao.java
package com.hills.happytest.utils; import java.util.arraylist; import java.util.list; import com.mongodb.basicdbobject; import com.mongodb.dbcursor; import com.mongodb.dbobject; /** * class name: mongodbdao.java * function: * the data dao that mongodb operate. * modifications: * * @author administrator * @datetime 2014-10-29 下午1:57:58 * @version 1.0 */ public class mongodbdao { private static mongodbutil mongodb; // init. mongodbutil. static{ try { mongodb = new mongodbutil("test"); } catch (exception e) { e.printstacktrace(); } } /** * test create a blanket collection. * @param collname :collection name. */ public void createcollectiontest(string collname) { mongodb.createcollection(collname); } /** * test insert dbobject into collection. * @param collname collection name. */ public void inserttest(string collname) { dbobject dbs = new basicdbobject(); dbs.put("name", "gymyung"); dbs.put("age", 20); list<string> books = new arraylist<string>(); books.add("extjs"); books.add("mongdb"); books.add("java"); dbs.put("books", books); mongodb.insert(dbs, collname); } /** * test insert dbobject list into collection. * @param collname collection name. */ public void insertbatchtest(string collname) { list<dbobject> dbobjects = new arraylist<dbobject>(); dbobject jim2 = new basicdbobject("name", "jim2"); dbobject liuting = new basicdbobject(); liuting.put("name", "liuting"); liuting.put("age", "22"); dbobjects.add(jim2); dbobjects.add(liuting); mongodb.insertbatch(dbobjects, collname); } /** * test delete data by id. * @param collname collection name. * @return operate result code. */ public int deletebyidtest(string collname) { int counts = mongodb.deletebyid("54507d19cbbd7a385c129ef5", collname); return counts; } /** * test delete data by condition. * @param collname collection name. * @return operate result code. */ public int deletebydbstest(string collname) { dbobject jim2 = new basicdbobject("name", "jim2"); int count = mongodb.deletebydbs(jim2, collname); return count; } /** * test update data. * @param collname collection name. * @return operate result code. */ public int updatetest(string collname) { dbobject liuting = new basicdbobject(); dbobject liuting2 = new basicdbobject(); liuting2.put("$set", new basicdbobject("gender", "female")); int count = mongodb.update(liuting, liuting2, false, true, collname); return count; } /** * test find data with page. * @param collname collection name. * @return string list result. */ public list<string> findwithpagetest(string collname) { dbcursor cursor = mongodb.findwithpage(null, null, 0, 3, collname); return convertcursortolist(cursor); } /** * test find data with condition. * @param collname collection name. * @return string list result. */ public list<string> findwithconditiontest(string collname) { dbobject where = new basicdbobject(); where.put("age", new basicdbobject("$lte", 26)); where.put("gender", "female"); dbcursor cursor = mongodb.findnopage(where, null,collname); return convertcursortolist(cursor); } /** * test find data no page. * @param collname collection name. * @return string list result. */ public list<string> findnopagetest(string collname) { dbobject keys = new basicdbobject(); keys.put("_id", false); keys.put("name", true); keys.put("age", true); dbcursor cursor = mongodb.findnopage(null, keys, collname); return convertcursortolist(cursor); } /** * convert cursor to list. * @param cursor required dbcursor. * @return string list result. */ private list<string> convertcursortolist(dbcursor cursor) { list<string> results = new arraylist<string>(); while(cursor.hasnext()) { dbobject dbobject = cursor.next(); for(string key : dbobject.keyset()) { results.add("{"+key+":"+dbobject.get(key)+"}"); } } return results; } }
3. testactivity.java
package com.hills.happytest; import java.util.list; import android.app.activity; import android.app.alertdialog; import android.content.dialoginterface; import android.os.asynctask; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import com.hills.happytest.utils.mongodbdao; import com.hills.happytest.utils.mongodbutil; /** * class name: testactivity.java * function: * test mongodb operate on android device. * modifications: * * @author gym yung. * @datetime 2014-10-29 下午1:53:40 * @version 1.0 */ public class testactivity extends activity implements onclicklistener{ /************** component in layout. ***************/ private button mongotestbtn1; private button mongotestbtn2; private button mongotestbtn3; private button mongotestbtn4; private button mongotestbtn5; private button mongotestbtn6; private button mongotestbtn7; private button mongotestbtn8; // the object use to mongodb operate. private mongodbdao mongodbdao; // the collection name in mongodb. private string collname = "androiddb"; /************** operate code ********************/ private final int create_collection_test = 100; private final int insert_test = 101; private final int insert_batch_test = 102; private final int delete_by_id_test = 103; private final int delete_by_dbs_test = 104; private final int update_test = 105; private final int find_with_page_test = 106; private final int find_nopage_test = 107; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.mongodb_test); findviewandsetlistener(); mongodbdao = new mongodbdao(); } /** * function: * find view and set listener. * @author administrator * @datetime 2014-10-29 下午1:08:50 */ private void findviewandsetlistener() { mongotestbtn1 = (button) findviewbyid(r.id.mongodb_btn1); mongotestbtn2 = (button) findviewbyid(r.id.mongodb_btn2); mongotestbtn3 = (button) findviewbyid(r.id.mongodb_btn3); mongotestbtn4 = (button) findviewbyid(r.id.mongodb_btn4); mongotestbtn5 = (button) findviewbyid(r.id.mongodb_btn5); mongotestbtn6 = (button) findviewbyid(r.id.mongodb_btn6); mongotestbtn7 = (button) findviewbyid(r.id.mongodb_btn7); mongotestbtn8 = (button) findviewbyid(r.id.mongodb_btn8); mongotestbtn1.setonclicklistener(this); mongotestbtn2.setonclicklistener(this); mongotestbtn3.setonclicklistener(this); mongotestbtn4.setonclicklistener(this); mongotestbtn5.setonclicklistener(this); mongotestbtn6.setonclicklistener(this); mongotestbtn7.setonclicklistener(this); mongotestbtn8.setonclicklistener(this); } @override public void onclick(view v) { myasynctast myasynctast = new myasynctast(); switch(v.getid()){ case r.id.mongodb_btn1: myasynctast.execute(create_collection_test); break; case r.id.mongodb_btn2: myasynctast.execute(insert_test); break; case r.id.mongodb_btn3: myasynctast.execute(insert_batch_test); break; case r.id.mongodb_btn4: myasynctast.execute(delete_by_id_test); break; case r.id.mongodb_btn5: myasynctast.execute(delete_by_dbs_test); break; case r.id.mongodb_btn6: myasynctast.execute(update_test); break; case r.id.mongodb_btn7: myasynctast.execute(find_with_page_test); break; case r.id.mongodb_btn8: myasynctast.execute(find_nopage_test); break; } } /** * class name: testactivity.java * function: * execute internet task by async... * modifications: * * @author administrator * @datetime 2014-10-29 下午1:54:34 * @version 1.0 */ class myasynctast extends asynctask<object, object, object>{ @override protected object doinbackground(object... params) { object result = null; switch(integer.parseint(params[0].tostring())) { case create_collection_test: mongodbdao.createcollectiontest(collname); break; case insert_test: mongodbdao.inserttest(collname); break; case insert_batch_test: mongodbdao.insertbatchtest(collname); break; case delete_by_id_test: result = mongodbdao.deletebyidtest(collname); break; case delete_by_dbs_test: result = mongodbdao.deletebydbstest(collname); break; case update_test: result = mongodbdao.updatetest(collname); break; case find_with_page_test: result = mongodbdao.findwithpagetest(collname); break; case find_nopage_test: result = mongodbdao.findnopagetest(collname); break; } return result; } @suppresswarnings("unchecked") @override protected void onpostexecute(object result) { if(result instanceof integer) { showdialogwithtext("操作结果码:"+result.tostring()); }else if(result instanceof list) { string restext = ""; for(string res : ((list<string>) result)) { restext += res + "\n"; } showdialogwithtext("操作结果\n:"+restext); } super.onpostexecute(result); } } /** * function: * show dialog with text. * @author administrator * @datetime 2014-10-29 下午1:21:34 * @param text */ private void showdialogwithtext(string text) { alertdialog.builder builder = new alertdialog.builder(this); builder.seticon(r.drawable.ic_launcher); builder.settitle("mongodb操作结果"); builder.setmessage(text); builder.setneutralbutton("确定", new dialoginterface.onclicklistener() { @override public void onclick(dialoginterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } @override protected void ondestroy() { // close mongodb connection if it is not null. if(mongodbutil.getconnection() != null) { mongodbutil.getconnection().close(); } super.ondestroy(); } }
4. 添加权限
<uses-permission android:name="android.permission.internet"/>
更多关于android相关内容感兴趣的读者可查看本站专题:《android数据库操作技巧总结》、《android编程之activity操作技巧总结》、《android开发入门与进阶教程》、《android资源操作技巧汇总》、《android视图view技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。
上一篇: Android 实现滑动方法总结