-2

I am working on a ANDROID APP which's database is CLOUDANT stored on IBM's cloud. Actually I am working on PERSONALITY INSIGHTS service of IBM. I want to store quiz data to CLOUDANT database of specific user. I have manually added 2(Two) documents to CLOUDANT database. But I can not find the documentation to insert data to CLOUDANT database via ANDROID APP.

Insert Doc to CLOUDANT database

The above link provides documentation for Reading & Inserting Doc to CLOUDANT Database under heading of Insert & Read A Document but not for ANDROID.

Sample Android App GitHub - CLOUDANT

I was referring above link but I think that example is out of syllabus for me.

What I have tried till is like below..

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();
    }
}

I can also read the data through https://$USERNAME.cloudant.com/$DATABASE/_all_docs. in browser.

Getting Data Image

Any help will be very very appreciable. Thanks in advance.

Community
  • 1
  • 1
Maulik Dodia
  • 1,629
  • 2
  • 21
  • 48

2 Answers2

2

Update: Dated:- 18.Feb.2016

You can just create document with necessary data like below using volley library.

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

Where _id is document id which you can give. It is also optional. But from my end, you should give your specific document id/name. If you do not give _id, it will take some random _id automatically which is unique. If document successfully created, you will get below response.

{ "ok":true, "id":"id given by you", "rev":"1-2902191555" }

For more information on this refer this OFFICIAL DOC.

Maulik Dodia
  • 1,629
  • 2
  • 21
  • 48
1

Below is my code.....

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>

Put preferences.xml file in res > xml. You have to make xml folder in res.

Maulik Dodia
  • 1,629
  • 2
  • 21
  • 48