欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android编程连接MongoDB及增删改查等基本操作示例

时间:2021-07-23 07:38:59|栏目:Android代码|点击:

本文实例讲述了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使用vitamio插件实现视频播放器

栏    目:Android代码

下一篇:Android之Notification的多种用法实例

本文标题:Android编程连接MongoDB及增删改查等基本操作示例

本文地址:http://www.codeinn.net/misctech/160683.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有