Search code examples
androidftpandroid-asynctaskftp-server

AsyncTask on ftp project


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.


Solution

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