I’m new to Android development and I’m building an app that gets contacts from the phone’s address book and saves them to a remote database using REST calls.
I can successfully read contacts from the device but I’m having trouble with the database insertion part. Here’s what the API expects:
Data format for saving:
[{'operation':'saveContact',
'name':'John',
'surname':'Smith',
'phone': '98765432'}]
Request format for reading:
[{'operation':'getContacts'}]
I’ve been trying different approaches but my POST request doesn’t seem to work. Here’s my current implementation:
public static HttpResponse sendPostRequest(String endpoint, JSONObject data) throws ClientProtocolException, IOException
{
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost postRequest = new HttpPost(endpoint);
StringEntity entity = new StringEntity(data.toString());
entity.setContentEncoding("UTF-8");
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
postRequest.setEntity(entity);
postRequest.addHeader("accept", "application/json");
return client.execute(postRequest);
}
And here’s my async task:
public class ContactUploader extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... args) {
JSONObject contactData = new JSONObject();
try
{
contactData.put("operation", "saveContact");
contactData.put("name", "John");
contactData.put("surname", "Smith");
contactData.put("phone", "98765432");
NetworkHelper.sendPostRequest(Config.apiUrl, contactData);
}
catch (JSONException ex)
{
ex.printStackTrace();
Log.e("JSON Error: ", ex.toString());
}
catch (ClientProtocolException ex)
{
ex.printStackTrace();
Log.e("Protocol Error: ", ex.toString());
}
catch (IOException ex)
{
ex.printStackTrace();
Log.e("IO Error: ", ex.toString());
}
Log.d("COMPLETE ", "Request finished");
return null;
}
}
The code runs without errors but no data appears in the database. What could be wrong with my approach?