如何从ANDROID应用程序在CLOUDANT数据库中插入数据

如何从ANDROID应用程序在CLOUDANT数据库中插入数据,android,cloudant,Android,Cloudant,我正在开发一个ANDROID应用程序,它的数据库是CLOUDANT,存储在IBM的云上。实际上,我正在IBM的Personal INSIGHTS服务上工作。我想将测验数据存储到特定用户的CLOUDANT数据库中。我已手动向CLOUDANT数据库添加了两(2)个文档。但是我找不到通过ANDROID应用程序将数据插入CLOUDANT数据库的文档 上述链接提供了插入和读取文档标题下的读取和插入文档到CLOUDANT数据库的文档,但不适用于ANDROID。 我指的是上面的链接,但我认为这个例子超出了

我正在开发一个ANDROID应用程序,它的数据库是CLOUDANT,存储在IBM的云上。实际上,我正在IBM的Personal INSIGHTS服务上工作。我想将测验数据存储到特定用户的CLOUDANT数据库中。我已手动向CLOUDANT数据库添加了两(2)个文档。但是我找不到通过ANDROID应用程序将数据插入CLOUDANT数据库的文档

上述链接提供了插入和读取文档标题下的读取和插入文档到CLOUDANT数据库的文档,但不适用于ANDROID。

我指的是上面的链接,但我认为这个例子超出了我的教学大纲

我所尝试的如下所示

格雷德尔先生

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>
我还可以通过计算机读取数据
https://$USERNAME.cloudant.com/$DATABASE/\u all\u文档。
在浏览器中

任何帮助都是非常可观的。提前感谢。

下面是我的代码

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;
    }
}
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>xml中。您必须在res.中创建xml文件夹更新:日期:2016年2月18日

您可以使用volley库创建包含必要数据的文档,如下所示

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);
stringurl=”https://cloudantUsername.cloudant.com/“+DB_名称;
RequestQueue RequestQueue=Volley.newRequestQueue(getContext());
HashMap=newHashMap();
map.put(“_id”,“Document id What What you want”);
map.put(“twitter_提要”、“您的数据”);
JsonObjectRequest jar1=新的JsonObjectRequest(Request.Method.POST、url、新的JSONObject(map)、新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
JSONObject=newJSONObject(response.toString());
REV=jsonObject.getString(“REV”);
}捕获(JSONException e){
}
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
Log.e(“Json错误:”,“+错误);
}
});
add(jar1);
其中
\u id
是您可以提供的文档id。它也是可选的。但从我的角度来看,您应该给出您的特定文档id/名称。如果您不提供
\u id
,它将自动获取一些唯一的随机
\u id
。若文档创建成功,您将得到以下响应

{
“ok”:没错,
“id”:“您提供的id”,
“修订版”:“1-2902191555”
}

有关这方面的更多信息,请参阅

<?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>
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);