Alexander
Alexander

Reputation: 35

Android AsyncTask freezes UI

I'm trying to get the data from server. Somehow the UI freezes despite the fact that I do all the connecting and extracting data in doinbackground method. I'll very appreciate if someone will help me, cause I examined all the questions on this topic and didn't find the solution.

public class GetMessagesActivity extends AsyncTask<String, Void, String> {
    private Context context;

    private ProgressDialog progressDialog;

    public GetMessagesActivity(Context context) {

        this.context = context;
        this.progressDialog = new ProgressDialog(context);
        this.progressDialog.setCancelable(false);
        this.progressDialog.setMessage("Updating...");
        this.progressDialog.show();

    }

    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... arg0) {
        try {
            String pid = "1";
            String link = "somelink";
            String data = URLEncoder.encode("pid", "UTF-8") + "="
            + URLEncoder.encode(pid, "UTF-8");
            // data += "&" + URLEncoder.encode("password", "UTF-8")
            // + "=" + URLEncoder.encode(password, "UTF-8");
            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(
            conn.getOutputStream());
            wr.write(data);
            wr.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            // Read Server Response
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }

            return sb.toString();
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        if (this.progressDialog != null) {
            this.progressDialog.dismiss();
        }
    }
}

Upvotes: 1

Views: 3274

Answers (1)

Al&#233;cio Carvalho
Al&#233;cio Carvalho

Reputation: 13657

You are probably misusing the AsyncTask. You should call it externally like this:

  new YourAsyncTask().execute();

if you are calling like this: "new YourAsyncTask().get()" it will block the UI thread.

See some usage reference here: http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 7

Related Questions