Android: Error adding data to database

I’m trying to write data to local database. Below is my code:

    @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_user_profile);

    editTextPassword = (EditText) findViewById(R.id.password);
    editTextPasswordConfirm = (EditText) findViewById(R.id.confirmpassword);
    editTextFirstName = (EditText) findViewById(R.id.firstname);
    editTextLastName = (EditText) findViewById(R.id.lastname);
    editTextEmail = (EditText) findViewById(R.id.email);
    editTextDateOfBirth = (EditText) findViewById(R.id.dob);
    editTextCountry = (EditText) findViewById(R.id.nationality);
    editTextName = (EditText) findViewById(R.id.name);

    buttonReset = (Button) findViewById(R.id.btn_reset);
    buttonUpdate = (Button) findViewById(R.id.btn_update);

    final String Name = editTextName.getText().toString();
    final String Password = editTextPassword.getText().toString();
    final String Email = editTextEmail.getText().toString();
    final String FirstName = editTextFirstName.getText().toString();
    final String LastName  = editTextLastName.getText().toString();
    final String DateOfBirth  = editTextDateOfBirth.getText().toString();
    final String Country  = editTextCountry.getText().toString();


    buttonUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyUtilities.hideSoftKey(UserProfileActivity.this,v);
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().execute("http://RestAPI_url/update-user");
        }
    });

    final String TAG = "HelloWorld";
    Log.d(TAG, "Begin Couchbase Party!");

    // create a manager
    Manager manager;
    try {
        manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
        Log.d (TAG, "Manager created");
    } catch (IOException e) {
        Log.e(TAG, "Cannot create manager object");
        return;
    }

    // create a name for the database and make sure the name is legal
    String dbname = "database";
    if (!Manager.isValidDatabaseName(dbname)) {
        Log.e(TAG, "Bad database name");
        return;
    }

    // create a new database
    Database database;
    try {
        database = manager.getDatabase(dbname);
        Log.d (TAG, "Database created");

    } catch (CouchbaseLiteException e) {
        Log.e(TAG, "Cannot get database");
        return;
    }

    String name = editTextFirstName.getText().toString();

    //create user object
    User myuser = new User();
    //Set username from text inside edittext
    myuser.setName(name);

    // create an object that contains data for a document
    Map<String, Object> docContent = new HashMap<String, Object>();
    docContent.put("message", "Hello Couchbase Lite");
    docContent.put("name", myuser.name);
    docContent.put("email", Email);
    docContent.put("password", Password);
    docContent.put("dateOfBirth", DateOfBirth);
    docContent.put("nationality", Country);
    docContent.put("firstname", FirstName);
    docContent.put("lastname", LastName);


    // display the data for the new document
    Log.d(TAG, "docContent=" + String.valueOf(docContent));

    // create an empty document
    Document document = database.createDocument();

    // add content to document and write the document to the database
    try {
        document.putProperties(docContent);
        Log.d (TAG, "Document written to database named " + dbname + " with ID = " + document.getId());
    } catch (CouchbaseLiteException e) {
        Log.e(TAG, "Cannot write document to database", e);
    }

    // save the ID of the new document
    String docID = document.getId();

    // retrieve the document from the database
    Document retrievedDocument = database.getDocument(docID);

    // display the retrieved document
    Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));

    // update the document
    Map<String, Object> updatedProperties = new HashMap<String, Object>();
    updatedProperties.putAll(retrievedDocument.getProperties());
    updatedProperties.put ("message", "We're having a heat wave!");
    updatedProperties.put ("temperature", "95");

    try {
        retrievedDocument.putProperties(updatedProperties);
        Log.d(TAG, "updated retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
    } catch (CouchbaseLiteException e) {
        Log.e (TAG, "Cannot update document", e);
    }

    // delete the document
    /*
    try {
        retrievedDocument.delete();
        Log.d (TAG, "Deleted document, deletion status = " + retrievedDocument.isDeleted());
    } catch (CouchbaseLiteException e) {
        Log.e (TAG, "Cannot delete document", e);
    } */

    Log.d(TAG, "End Hello World App");

}
public static String POST(String url, User user){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", user.getName());
        jsonObject.accumulate("password", user.getPassword());
        jsonObject.accumulate("email", user.getEmail());
        jsonObject.accumulate("firstname", user.getFirstName());
        jsonObject.accumulate("surname", user.getSurname());
        jsonObject.accumulate("dateOfBirth", user.getDateOfBirth());
        jsonObject.accumulate("nationality", user.getNationality());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(user);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}


    private class HttpAsyncTask extends AsyncTask<String, Void, String> {

    String name = editTextName.getText().toString();
    String password = editTextPassword.getText().toString();
    String email = editTextEmail.getText().toString();

    @Override
    protected String doInBackground(String... urls) {

        user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setEmail(email);

        return POST(urls[0],user);
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
      }
    }

   }

And below is the log output:

  D/HelloWorld: Database created
  D/HelloWorld: docContent={nationality=, password=, dateOfBirth=, lastname=, email=, name=, firstname=, message=Hello Couchbase Lite}
  D/HelloWorld: Document written to database named database with ID = 619963cc-6a32-4fae-a32e-fa038d34d7c0
  D/HelloWorld: retrievedDocument={nationality=, _rev=1-5189faf0be98a2063c18aa09f2115e4e, password=, dateOfBirth=, name=, lastname=, email=, firstname=, _id=619963cc-6a32-4fae-a32e-fa038d34d7c0, message=Hello Couchbase Lite}
  D/HelloWorld: updated retrievedDocument={nationality=, _rev=2-5f088bb238e7db472ccd6e08965d6a3b, password=, temperature=95, dateOfBirth=, email=, lastname=, name=, firstname=, _id=619963cc-6a32-4fae-a32e-fa038d34d7c0, message=We're having a heat wave!}
  D/HelloWorld: End Hello World App
  I/ViewRootImpl: CPU Rendering VSync enable = true

What’s your question? I don’t see any error in the log, and the output seems consistent with your code.

My problem is that as seen below, some variables in the document are empty. I can’t assign values to them from the edittexts.

From what you posted, it looks like you’re assigning the strings during your onCreate method. That’s setting up the UI. The edit text views will all be empty. Am I missing something? Otherwise, you need to put the assignments in a callback.

I’m not quite sure I understand. Could you please answer me with some code?

Sure. I just coded this simplified version. Notice I implemented the button click listener on the activity instead of using an anonymous class. It’s slightly cleaner in this case. Take a look. (I didn’t test this, but it should be ok.)

package com.couchbase.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Document;
import com.couchbase.lite.Manager;
import com.couchbase.lite.android.AndroidContext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private static String TAG = "HelloWorld";

    private static String dbname = "database";

    private EditText editTextEmail;
    private Button buttonUpdate;

    private Database database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextEmail = (EditText) findViewById(R.id.email);

        //buttonReset = (Button) findViewById(R.id.btn_reset);
        buttonUpdate = (Button) findViewById(R.id.btn_update);

        buttonUpdate.setOnClickListener(this);

        Log.d(TAG, "Begin Couchbase Party!");

        // create a manager
        Manager manager;
        try {
            manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
            Log.d(TAG, "Manager created");
        } catch (IOException e) {
            Log.e(TAG, "Cannot create manager object");
            return;
        }

        // create a name for the database and make sure the name is legal
        if (!Manager.isValidDatabaseName(dbname)) {
            Log.e(TAG, "Bad database name");
            return;
        }

        // create a new database
        try {
            database = manager.getDatabase(dbname);
            Log.d(TAG, "Database created");
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Cannot get database");
            return;
        }

        Log.d(TAG, "End onCreate");
    }

    @Override
    public void onClick(View v) {
        /*
        MyUtilities.hideSoftKey(UserProfileActivity.this,v);

        if (!validate()) {
            Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            return;
        }
         */
        // create an object that contains data for a document

        final String Email = editTextEmail.getText().toString();

        Map<String, Object> docContent = new HashMap<String, Object>();
        docContent.put("message", "Hello Couchbase Lite");
        docContent.put("email", Email);

        // display the data for the new document
        Log.d(TAG, "docContent=" + String.valueOf(docContent));

        // create an empty document
        Document document = database.createDocument();

        // add content to document and write the document to the database
        try {
            document.putProperties(docContent);
            Log.d (TAG, "Document written to database named " + dbname + " with ID = " + document.getId());
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Cannot write document to database", e);
        }

        // save the ID of the new document
        String docID = document.getId();

        // retrieve the document from the database
        Document retrievedDocument = database.getDocument(docID);

        // display the retrieved document
        Log.d(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));

        // update the document
        Map<String, Object> updatedProperties = new HashMap<String, Object>();
        updatedProperties.putAll(retrievedDocument.getProperties());
        updatedProperties.put ("message", "We're having a heat wave!");
        updatedProperties.put ("temperature", "95");

        try {
             retrievedDocument.putProperties(updatedProperties);
            Log.d(TAG, "updated retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
        } catch (CouchbaseLiteException e) {
            Log.e (TAG, "Cannot update document", e);
        }
    }
}
1 Like