0

I'm a beginner Android programmer and I am working on a program that reads Contacts from native device phonebook and writes them to database ( ).

I can get and read the contacts from my mobile phone, but I'm stuck at the "writing contacts to database". This is the guideline I have to follow:

write function: 
write: 
[{'activity':'writeData', 
  'firstname':'Janis', 
  'lastname':'Berzins', 
  'telnr': '12312312'}]

request should be sent as: [{'activity':'readData'}]

example for read: [{"firstname":"Vards","lastname":"Uzvards","telnr":"12345678"},{"firstname":"Viesturs","lastname":"Lapsa","telnr":"11223344"}]

I researched countless tutorials, documentations and so on, for four days and this is what I thought should work for the sending to database part:

public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
{
    HttpParams httpParams = new BasicHttpParams();
    HttpClient httpclient = new DefaultHttpClient(httpParams);
    HttpPost request = new HttpPost(url);
    StringEntity s = new StringEntity(c.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    return httpclient.execute(request);
}

And to create a simple test Json I used this class:

    public class RestPost extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... params) {
        JSONObject json = new JSONObject();

        try
        {
            json.put("activity", "writeData");
            json.put("firstname", "Janis");
            json.put("lastname", "Berzins");
            json.put("telnr", "123123123");

            RestMethods.doPost(Main.server, json);
        }

        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        catch (ClientProtocolException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Error: ", e.toString());
        }
        Log.i("DONE ", " I GUES");
        return null;
    }
}

But after my Android app executes this function - nothing has changed in the database ().

So, please, can anyone help me figure out, what am I doing wrong?

Thank you!

EdvardsMC
  • 1
  • 1

2 Answers2

0

You need an json array (see the "[" and "]" characters around the json within the spec.

    JSONArray jsonArray = new JSONArray();
    // your code to create the JSONObject
    // ...
    jsonArray.put(json);

    // use this within your RestMethods call
    RestMethods.doPost(Main.server, jsonArray);

You probably can send multiple objects to the server at once - even though the "spec" doesn't mention it, the use of an array is a hint that you can.

Wolfram Rittmeyer
  • 2,402
  • 1
  • 18
  • 21
  • I changed the method - to send a JASONArray, but still nothing seams to be sent to the database :( – EdvardsMC Apr 14 '13 at 11:39
  • So exactly what is arriving at the server. Did you try to get the data via wireshark or at least some logging on the server side? – Wolfram Rittmeyer Apr 14 '13 at 19:00
  • I'm not that good with wireshark, but I can see there that my aplication is sending this: 190 7.674770000 10.2.5.231 194.213.101.181 HTTP 353 POST /api.php HTTP/1.1 (application/json) – EdvardsMC Apr 14 '13 at 20:02
  • But whats weird is that the segment is something like this: [write=[{"telnr":"123123123","lastname":"Bush","activity":"writedata","firstname":"John"}]] And my "spec" said that it should be in a different order - or it doesnt matter? – EdvardsMC Apr 14 '13 at 20:06
  • And also - if I print out the HttpResponse I get the message "json tuksh" .. the same text you can see when opening the database link: http://mongo.tdlbox.com/api.php – EdvardsMC Apr 14 '13 at 20:12
  • `write = [{...}]`? Shouldn't it be `write: [{...}]` if a function name at all is necessary. The order shouldn't be relevant. From the spec: "An object is an unordered set of name/value pairs." – Wolfram Rittmeyer Apr 15 '13 at 12:06
  • Yes, I think it should, but how can I change the "=" sign to ":"? This is what I'm using to send data: List nvps = new ArrayList(); nvps.add(new BasicNameValuePair("write", c.toString())); request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); Also, is it ok that I send you an e-mail, for more questions? And thanks for your help so far! :) – EdvardsMC Apr 15 '13 at 15:43
  • I even tried to send it like this: String body = String.format("write:[{\'activity\':\'writeData\',\'firstname\':\'%s\',\'lastname\':\'%s\',\'telnr\':\'%s\'}]","John","Bush","123123123"); .. but still - no change – EdvardsMC Apr 15 '13 at 16:14
  • Ha :D It was my fault - the data is being sent to the database, sorry - now I'm working on retrieving the data, can You please check my Get function .. I'll post it bellow! :) – EdvardsMC Apr 15 '13 at 17:31
  • If you needed the JSONArray, you should at least vote this answer up. If I understand it correctly it was at least _one_ of your problems, wasn't it? – Wolfram Rittmeyer Apr 15 '13 at 19:00
  • Yeah, but how do I vote it up - because it says I need to have reputation at least 15 – EdvardsMC Apr 15 '13 at 20:29
0

Ok, I got it working with sending to the database! :) Now I'm working with the Get method.. this is what I got - and for now it seems not to be working, possibly due to the fact that the data in database is sent as JSONArray?

public static JSONObject doGet(String url)
{
    JSONObject json = null;

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url); 

    httpget.addHeader("accept", "application/json");
    HttpResponse response;

    try {
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();    

        if (entity != null) 
        {
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            json=new JSONObject(result);     
            instream.close();
        }   
    } 

    catch (ClientProtocolException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 

    catch (JSONException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    }        

    return json;
}

public static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try 
    {
        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
        Log.i("Error: ", e.toString());
    } 
    finally 
    {
        try 
        {
            is.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    return sb.toString();
} 
EdvardsMC
  • 1
  • 1