5

I want to implement a class which will handle all HTTP Requests of my application, which will be basically:

  • Get a list of business (GET);
  • Execute a login (POST);
  • Update the location (POST).

So, I will have to get the result string from the server (JSON) and pass it to another methods to handle the responses.

I currently have this methods:

public class Get extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... arg) {
        String linha = "";
        String retorno = "";

        mDialog = ProgressDialog.show(mContext, "Aguarde", "Carregando...", true);

        // Cria o cliente de conexão
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(mUrl);

        try {
            // Faz a solicitação HTTP
            HttpResponse response = client.execute(get);

            // Pega o status da solicitação
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) { // Ok
                // Pega o retorno
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                // Lê o buffer e coloca na variável
                while ((linha = rd.readLine()) != null) {
                    retorno += linha;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return retorno;
    }

    @Override
    protected void onPostExecute(String result) {
        mDialog.dismiss();
    }
}

    public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
        // Determina a URL
        setUrl(url);

        // Executa o GET
        Get g = new Get();

        // Retorna o jSON
        return createJSONObj(g.get());
    }

But the g.get() returns a empty response. How can I fix that?

secretformula
  • 6,414
  • 3
  • 33
  • 56
Danniel Magno
  • 304
  • 1
  • 3
  • 21
  • add a log statement to your doInBackground that logs the String returno after the get has been finished to make sure a message is being returned. – coder_For_Life22 Jan 12 '12 at 01:57

3 Answers3

14

I think you didn't understand exactly the way AsyncTask works. But I believe you wish to reuse the code for different tasks; if so, you can create an abstract class and then extend it implementing an abstract method you created. It should be done like this:

public abstract class JSONTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... arg) {
        String linha = "";
        String retorno = "";
        String url = arg[0]; // Added this line

        mDialog = ProgressDialog.show(mContext, "Aguarde", "Carregando...", true);

        // Cria o cliente de conexão
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(mUrl);

        try {
            // Faz a solicitação HTTP
            HttpResponse response = client.execute(get);

            // Pega o status da solicitação
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) { // Ok
                // Pega o retorno
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                // Lê o buffer e coloca na variável
                while ((linha = rd.readLine()) != null) {
                    retorno += linha;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return retorno; // This value will be returned to your onPostExecute(result) method
    }

    @Override
    protected void onPostExecute(String result) {
        // Create here your JSONObject...
        JSONObject json = createJSONObj(result);
        customMethod(json); // And then use the json object inside this method
        mDialog.dismiss();
    }

    // You'll have to override this method on your other tasks that extend from this one and use your JSONObject as needed
    public abstract customMethod(JSONObject json);
}

And then the code on your activity should be something like this:

YourClassExtendingJSONTask task = new YourClassExtendingJSONTask();
task.execute(url);
Beowulf Bjornson
  • 1,626
  • 1
  • 14
  • 24
1

You are not executing the task. You are just creating it. I think you need to make:

Get g = new Get();
g.execute();

But you are using the lifecycle of the task in a wrong way. OnPostExecute runs on the Main thread, where you should do all the updates as needed. You can pass the task a View for example.

sebastianf182
  • 9,844
  • 3
  • 34
  • 66
  • I thought the get() method calls the execute(), because the documentation says that it waits the computation to finish... All right, I'll try call it before. – Danniel Magno Jan 12 '12 at 02:25
  • So how can I handle the dialog to appear while the request is being executed and to dismiss when it's done? – Danniel Magno Jan 12 '12 at 02:27
  • 1
    That might be right, but the return value doesnt come from the .get method, it goes to your OnPostExecute. See the String that comes into the method. Thats your response from the HTTPConnection. – sebastianf182 Jan 12 '12 at 02:33
  • You are handling the Dialog just fine. The problem is that the String you want is this one: protected void onPostExecute(String result). Thats where the return from the doInBackground goes. – sebastianf182 Jan 12 '12 at 02:36
  • and `.get()` runs on the main thread, effectively rendering the usage of a `AsyncTask` void – slinden77 Jun 29 '16 at 19:28
1

It appears that you are never actually starting the AsyncTask by calling the execute() function on the Get object.

try this code:

Get g = new Get();
g.execute();
ErasmoOliveira
  • 1,416
  • 2
  • 20
  • 40
Wizetux
  • 756
  • 3
  • 12