Search code examples
androidandroid-asynctaskandroid-networking

onPostExecute doesn't get called


I have the following code to execute a PHP script:

public class CallPHPScript extends AsyncTask<ScriptNameAndParameters, Void, String> {
    private Reply responder;

    public interface Reply {
        public void serverReply(String reply);
    }

    public CallPHPScript(Reply r) {
        responder = r;
    }

    @Override 
    protected String doInBackground(ScriptNameAndParameters... arg) {
        List<NameValuePair> params = arg[0].getParameters();
        String scriptName = arg[0].getScriptName();
        String json = MainActivity.makeCall(scriptName, params);
        return json;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d("SERVER REPLY", "Server Reply: " + result);
        responder.serverReply(result);
    }

}

public static String makeCall(String scriptName, List<NameValuePair> params) {
    String address = SERVER_ADDRESS + scriptName + ".php";

    Log.d("Main Activity", "Making call to server with: " + address);

    HttpPost httpPost = new HttpPost(address);
    HttpClient httpClient = new DefaultHttpClient();
    StringBuilder total = new StringBuilder();
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        // Execute HTTP Post Request
        HttpResponse response = httpClient.execute(httpPost);
        InputStream is = response.getEntity().getContent();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line = "";
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }

        // Return full string
        Log.d("CALLPHPSCRIPT", total.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }
    return total.toString();
}

While it seems to work ok, the only output I can see is

        // Return full string
        Log.d("CALLPHPSCRIPT", total.toString())

This line (and therefore my callback)

    Log.d("SERVER REPLY", "Server Reply: " + result);

never get called. Does anybody have any idea where I'm going wrong?


Solution

  • Just realised I'm supposed to call

        CallPHPScript callPHP = new CallPHPScript(this);
        callPHP.execute(new ScriptNameAndParameters("get_all_profiles",new ArrayList<NameValuePair>()));
    

    instead of

        CallPHPScript callPHP = new CallPHPScript(this);
        callPHP.doInBackground(new ScriptNameAndParameters("get_all_profiles",new ArrayList<NameValuePair>()));
    

    Doh!