我正在开发一个 ANDROID APP ,其数据库 CLOUDANT 存储在 IBM的云中。其实我正在研究 IBM 的PERSONALITY INSIGHTS服务。我想将测验数据存储到特定用户的 CLOUDANT 数据库。我已手动将2(2)个文档添加到 CLOUDANT 数据库。但我找不到通过 ANDROID APP 将数据插入 CLOUDANT 数据库的文档。
Insert Doc to CLOUDANT database
上面的链接提供了阅读和阅读的文档。将文档插入CLOUDANT数据库,标题为插入&阅读文档但不适用于 ANDROID。
Sample Android App GitHub - CLOUDANT
我在上面提到的链接,但我认为这个例子对我来说不是教学大纲。
我尝试过的事情如下所示..
的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.android02.cloudant_db_demo_app"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile (group: 'com.cloudant', name: 'cloudant-sync-datastore-android', version:'latest.release')
}
的settings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_user">USERNAME</string>
<string name="default_dbname">DATABASE</string>
<string name="default_api_key">API KEY</string>
<string name="default_api_password">API PWD</string>
</resources>
MainActivity.java
package com.example.android02.cloudant_db_demo_app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.cloudant.sync.datastore.MutableDocumentRevision;
public class MainActivity extends AppCompatActivity {
static final String SETTINGS_CLOUDANT_USER = "USERNAME";
static final String SETTINGS_CLOUDANT_DB = "DATABASE";
static final String SETTINGS_CLOUDANT_API_KEY = "API KEY";
static final String SETTINGS_CLOUDANT_API_SECRET = "API PWD";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MutableDocumentRevision rev = new MutableDocumentRevision();
}
}
我也可以通过阅读数据
浏览器中的https://$USERNAME.cloudant.com/$DATABASE/_all_docs.
。
任何帮助都会非常明显。提前致谢。
答案 0 :(得分:1)
以下是我的代码.....
MainActivity.java
package com.cloudant_db_demo.android02.cloudant_db_demo;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DatastoreNotCreatedException;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.replication.Replicator;
import com.cloudant.sync.replication.ReplicatorBuilder;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener {
private Replicator PushReplicator;
private Datastore DataStore;
private static final String DATASTORE_MANGER_DIR = "data";
private static final String TASKS_DATASTORE_NAME = "tasks";
static final String CLOUDANT_USER = "key_username";
static final String CLOUDANT_DB = "key_dbname";
static final String CLOUDANT_API_KEY = "api_key";
static final String CLOUDANT_API_SECRET = "api_pwd";
Button btn_insert_data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
btn_insert_data.setOnClickListener(this);
}
void init() {
setDefaultConfigurations();
btn_insert_data = (Button) findViewById(R.id.btn_insert_data);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_insert_data:
insertDatatoCloud();
break;
default:
}
}
void setDefaultConfigurations() {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
try {
DataStore = manager.openDatastore(TASKS_DATASTORE_NAME);
reloadConfiguration();
} catch (DatastoreNotCreatedException e) {
Toast.makeText(getApplicationContext(), "Unable to open Datastore!", Toast.LENGTH_SHORT).show();
} catch (URISyntaxException e2) {
Toast.makeText(getApplicationContext(), "There is some error while connecting to server2!!", Toast.LENGTH_SHORT).show();
}
}
void insertDatatoCloud() {
createDocument();
PushReplicator.start();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
try {
reloadConfiguration();
} catch (URISyntaxException e) {
Toast.makeText(getApplicationContext(),
"There is some error while connecting to server!!",
Toast.LENGTH_LONG).show();
}
}
void reloadConfiguration() throws URISyntaxException {
URI uri = this.createServerURI();
PushReplicator = ReplicatorBuilder.push().from(DataStore).to(uri).build();
PushReplicator.getEventBus().register(this);
}
private URI createServerURI() throws URISyntaxException {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = sharedPref.getString(MainActivity.CLOUDANT_USER, "");
String dbName = sharedPref.getString(MainActivity.CLOUDANT_DB, "");
String apiKey = sharedPref.getString(MainActivity.CLOUDANT_API_KEY, "");
String apiSecret = sharedPref.getString(MainActivity.CLOUDANT_API_SECRET, "");
String host = username + ".cloudant.com";
return new URI("https", apiKey + ":" + apiSecret, host, 443, "/" + dbName, null, null);
}
void createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
BasicDocumentRevision created = DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
Toast.makeText(getApplicationContext(), "Document is not created!!", Toast.LENGTH_SHORT).show();
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
SettingsActivity.java
package com.cloudant_db_demo.android02.cloudant_db_demo;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
的preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:defaultValue="Username of Cloudant Here"
android:key="key_username"
android:summary="This is a default username."
android:title="Username " />
<EditTextPreference
android:defaultValue="test_db"
android:key="key_dbname"
android:summary="This is a default dbname."
android:title="Dbname " />
<EditTextPreference
android:defaultValue="Api Key Value"
android:key="api_key"
android:summary="This is a default API key."
android:title="API Key " />
<EditTextPreference
android:defaultValue="Api Key Password"
android:key="api_pwd"
android:summary="This is a default API password."
android:title="API Password " />
</PreferenceScreen>
将preferences.xml文件放入res&gt; XML。您必须在res。
中创建xml文件夹答案 1 :(得分:1)
更新:日期: - 18.Feb.2016
您可以使用排球库创建包含如下所需数据的文档。
String url = "https://cloudantUsername.cloudant.com/" + DB_NAME;
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("_id", "Document Id What-Ever you want");
map.put("twitter_feeds", "Your Data");
JsonObjectRequest jar1 = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
REV = jsonObject.getString("rev");
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Json Error Res: ", "" + error);
}
});
requestQueue.add(jar1);
_id
是您可以提供的文件ID。它也是可选的。但是从我的角度来看,你应该给你特定的文件ID /名称。如果您未提供_id
,则会自动采用一些随机_id
,这是唯一的。如果文档成功创建,您将得到以下响应。
{
"ok":true,
"id":"id given by you",
"rev":"1-2902191555"
}
有关详细信息,请参阅此OFFICIAL DOC。