2

I have an android application that communicates with WebService. My application sends request to Web Service which is written in php. The php side, just processes the request and echo out result in JSON format.

Although amount of data being transferred is minimal, sometimes it takes too long to load data in my app.

Here are methods in my android app that are responsible for Sending the request and retrieving response

/**
 * Posts data to server.
 * 
 * @param url Server URL
 * @param json {@link JSONObject} to be sent
 * @param tag Tag. used to describe the request
 * @return {@link HttpResponse}
 * @throws IOException
 * @throws ClientProtocolException
 */
public HttpResponse postData(String url, JSONObject json, String tag)
        throws ClientProtocolException, IOException {
    SharedPreferences prefs = context.getSharedPreferences(SUPPORTDESK, Context.MODE_PRIVATE);
    HttpResponse httpResponse = null;

    String jsonString = json.toString();
    String encodedURL = URLEncoder.encode(jsonString, HTTP.UTF_8);

    List<NameValuePair> value = new ArrayList<NameValuePair>();
    value.add(new BasicNameValuePair("username", prefs.getString(USERNAME_KEY, "")));
    value.add(new BasicNameValuePair("password", prefs.getString(PASSWORD_KEY, "")));
    value.add(new BasicNameValuePair("tag", tag));
    value.add(new BasicNameValuePair("data", encodedURL));

    DefaultHttpClient httpClient = new DefaultHttpClient();
    //setTimeout(httpClient, 5000);
    HttpPost request = new HttpPost(url);

    // StringEntity entity = new StringEntity(jsonString);
    // request.setHeader("Content-Type", "application/json");
    // request.setEntity(entity);
    request.setEntity(new UrlEncodedFormEntity(value, HTTP.UTF_8));

    httpResponse = httpClient.execute(request);

    return httpResponse;

}

/**
 * Retrieves String representation of {@link HttpResponse}
 * 
 * @param response {@link HttpResponse}
 * @return <b>String</b> Actual Response from server as string.
 * @throws IOException
 * @throws IllegalStateException
 * @throws UnsupportedEncodingException
 */
public static String getServerResponse(HttpResponse response)
        throws IOException, IllegalStateException,
        UnsupportedEncodingException {

    InputStream is = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,
            HTTP.UTF_8), 100);
    StringBuilder sb = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }

    is.close();
    String out = URLDecoder.decode(sb.toString().trim(), HTTP.UTF_8).trim();
    int ascii = (int) out.charAt(0);

    return (ascii >= 33 & ascii <= 126)?out:out.substring(1);
}

postData method will send the request and waits for the response, the response then will pass to getServerResponse to retrieve string representation of the response. And of course all long-Running codes are wrapped in AsyncTask class.

and here is a sample method of my web service:

function transactionDetail($json) {
    $array = json_decode($json, TRUE);
    $db = new DBHelper();
    $transactionId = $array[$db->JS_RP_TRANSACTION_ID];
    $response = $db->getTransactionDetails($transactionId);
    echo urlencode(json_encode($response));
}

So, is the method i'm using on Android Side for making the request and retrieving the response, Standard way to do it, or there is a better way ?

How can i set timeout for the request i make ?, you can see a commented line in my code, i tried to set a timeout but it broke the code.

And is the combination of Client/Server side code i'm using good enough or there is more standard or improved way to achieve this that i dont know of ?

Nevercom
  • 840
  • 3
  • 14
  • 38
  • 1
    I think some useful info you can provide is "how long is too long to load the data? time wise" are we talking, 1 sec, 10 secs? Also, have you thought about settings timers to see what part of the code actually is taking too long? Is it client or server? – LuckyMe Aug 14 '13 at 08:04
  • I was looking for some insight on this too! What time is good time for network interaction, will keep a watch over this space. – Skynet Aug 14 '13 at 08:07
  • @LuckyMe The thing is, sometimes it takes ~2-3 seconds, sometimes it takes too long (~20 sec or more) and the amount of data being transferred is less than 50KB most times. Could you provide me more info about setting timers ? thanks – Nevercom Aug 14 '13 at 08:17
  • @Nevercom Check this link, and try to do it between each major operation to see the ones taking too long: http://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java#answer-180191 – LuckyMe Aug 14 '13 at 09:06
  • @LuckyMe Actually I've heard of `Volley` library just now, I'm gonna give it a try. – Nevercom Aug 14 '13 at 09:17

1 Answers1

2

I am using the exact same code to update a database in my app, i am sending with php/echo/json a large amount of data, and the only time i have experienced a slow down is when the internet speed is low or the server gets slow.

After upgrading to a better server the only time this operation takes a few seconds to finish is when the signal strength gets low on the phone and the data transfer slows down to dial up speeds or lower....

Your php code and java codes are correct, i suspect the problem is with your server. You should do testing when your phone is on wi-fi with good signal strenght to rule out the net speed, and test how long it takes for your DB HELPER in php to get the results. If its SQL connection and not Mongo or something else it should work faster than 50ms even for 10 000 rows for results. (taking from my own experience)

JanBo
  • 2,925
  • 3
  • 23
  • 32