ali
ali

Reputation: 11045

Send HttpPost with Async and get string result

I am relatively a new Android developer and I am not able to understand how to do this. I have been looking through all the forums, I made some advance but still here I am. So, what I want to do is a common function that send a POST request to a webpage (it only sends one POST argument) and returns the result as a string. I have the main thread here

public class AppActivity extends Activity {
    HTTPPostData PostData = new HTTPPostData("id");
    PostData.execute();
    txtLabel.setText(PostData.Result);
}

and I have my HTTPPostData asynchronous class

public class HTTPPostData extends AsyncTask<String, Long, Object> {
String Value = null;
String Result = null;

public HTTPPostData(String query) {
    Value = query;
    }

@Override
protected String doInBackground(String... params) {
    byte[] Bresult = null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.mypage.com/script.php");
        try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("cmd", Value));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            HttpResponse response = client.execute(post);
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
                Bresult = EntityUtils.toByteArray(response.getEntity());
                Result = new String(Bresult, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }
        return Result;
    }
}

I want to use this function several times (inside the same Activity or share it with other Activities of the same application). I am a little bit messed up at this moment so I need your help. What I understand is that I am asking for the result before the doInBackground() is done, and I get an empty result.

Thanks in advance for your help

Upvotes: 0

Views: 2080

Answers (1)

Tim
Tim

Reputation: 35923

Regarding this:

HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText(PostData.Result);

Your problem is that you're treating asynctask like it's just a regular function. It's good that you move webpage loading off the main thread, but if you depend on the result for the very next instruction, then it's not doing you much good, you're still blocking the main program waiting for the result. You need to think of AsyncTask like a 'fire and forget' operation, in which you don't know when, if ever, it will come back.

The better thing to do here would be something like:

HTTPPostData PostData = new HTTPPostData("id");
PostData.execute();
txtLabel.setText("Loading...");

and then in the asynctask:

protected void onPostExecute(String result) {
     txtLabel.setText(result);
}

This lets your main thread get on with doing it's business without knowing the result of the asynctask, and then as soon as the data is available the asynctask will populate the text label with the result.

Upvotes: 1

Related Questions