開發環境是Eclipse+Android SDK+Mongodb+mongo-java-driver
Android的API是8(2.2),最低支持的是1.5,最高支持的是4.4。
Mongodb是用2.6.6
mongo-java-driver是2.13.0-rc2
我是做一個簡單的學生資料錄入的app。
原理是通過點擊 save的button,觸發SaveButton_Click,然後SaveButton_Click會把對應的
EditText的內容轉換成一個mongodb的文檔寫入數據庫。
編碼提示mongo的構造方法已經deprecated,
new Mongo();
new Mongo("localhost");
new Mongo("localhost", 27017);
new Mongo(new ServerAddress("localhost"));
上述4種debug軟件會有提示,在模擬器運行也會報錯。如何才能解決呢?
MainActivity.java的代碼:
package com.example.testing;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.mongodb.*;
public class MainActivity extends ActionBarActivity {
Button button;
int count=0;
String studentname;
String studentnum;
String studentage;
String studentsexual;
Mongo conn;
DB db;
DBCollection coll;
BasicDBObject doc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.saveButton);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("deprecation")
public void SaveButton_Click(View view)
{
try{
conn = new Mongo("localhost");
}catch (Exception e){
throw new RuntimeException(e);
};
DB db = conn.getDB("grade");
DBCollection coll = db.getCollection("Student");
BasicDBObject doc = new BasicDBObject();
doc.put("name", R.id.nameEditText);
doc.put("num",R.id.nameEditText);
doc.put("age",R.id.ageEditText);
doc.put("sexual",R.id.sexualEditText);
coll.setWriteConcern(WriteConcern.SAFE);
}
}
模擬器連接本地pc機不認localhost,應該是10.0.2.2
可以參見http://blog.csdn.net/lyq8479/article/details/6665104