Question

I have problem with asynctasks blocking UI when task download metafile from FTP server.

[Main.class] FragmentActivity

@Override
    public void onClick(View view) {

        TestSettings(); // TODO do usunięcia z kodu
        String password = this.password.getText().toString();

        boolean isConnected = false;

        try {
            isConnected = new TaskConnect(new ProgressDialog(getActivity().getApplicationContext()), password).execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        if (isConnected) {

            Toast.makeText(getActivity(), "Connected", Toast.LENGTH_LONG).show();

            try {

                boolean isListDownloaded = new TaskDownloadFilesList(new ProgressDialog(getActivity().getApplicationContext())).execute().get();

                if(isListDownloaded) {
                    getFragmentManager().beginTransaction()
                            .replace(R.id.container, new FragmentList(client.getList()))
                            .addToBackStack(this.getTag())
                            .commit();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }


        }


    }

[TaskDownloadFilesList.class] - AsyncTask

public class TaskDownloadFilesList extends AsyncTask <Boolean, Boolean, Boolean> {

    private static final FTP CLIENT = FTP.getInstance();
    private static ProgressDialog dialog = null;
    private static boolean isDownloaded = false;

    public TaskDownloadFilesList(ProgressDialog dialog) { this.dialog = dialog; }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Downloading list");
        dialog.setCancelable(false);
    }

    @Override
    protected Boolean doInBackground(Boolean... booleans) {

        dialog.show();

        if(CLIENT.isConnected()) {
            try { isDownloaded = CLIENT.checkList(); }
            catch (IOException e) { e.printStackTrace(); }
        }

        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        dialog.dismiss();
    }

    public boolean getResult() {
        return isDownloaded;
    }

In fact I use TaskConnect to connect to the FTP Server this task not freeze UI.

Was it helpful?

Solution

You are calling AsyncTask's get() which blocks the calling Thread until it finishes. Remove the get() calls.

OTHER TIPS

Instead of using get() method of AsyncTask, you may wait that task finish in doInBackground() method then add the code you want to execute in onPostExecute().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top