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