0

I'm trying to get into Android app development and as a test I'm trying to make an app download a simple web page in the background, while the main UI can be used. The user presses a 'search' button and the page is downloaded in a background task.


The code I have for this is as follows:

DownloadTask.java

//all the necessary package and import statements

public class DownloadTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... urls) {
        FPDownloader fpDownloader = new FPDownloader(context);
        if (fpDownloader.isConnected()) {
            return fpDownloader.download(urls[0]);
        }
        else {
            return null;
        }
    }

}

Where FPDownloader is a class I made. It downloads a web page and returns its content as a String.

SearchButtonListener.java

public class SearchButtonListener implements View.OnClickListener {

    private Activity context;
    private String type;
    private String category;
    private String page;

    public SearchButtonListener(Activity context, String type, String category, String page) {
        this.context = context;
        this.type = type;
        this.category = category;
        this.page = page;
    }

    public void onClick(View view) {
        String url = new FPUrlBuilder().getBrowseUrl(type, category, page);
        DownloadTask downloadTask = new DownloadTask(context);
        String result;

        TextView test = (TextView)context.findViewById(R.id.testTextView);

        try {
            downloadTask.execute(url);
            result = downloadTask.get();
            if (result != null) {
                test.setText("It worked! Downloaded " + url);
            }
            else {
                test.setText("Something went wrong while downloading the data");
            }
        }
        catch (Exception e) {
            //e.printStackTrace();
            test.setText("Something went wrong while executing the download");
        }
    }
}

Here FPUrlBuilder is another class I made, which simply returns an url based on the parameters you provide.

(If necessary, I can provide the activity's source aswell. Also, I know I'm passing Activity instances around- is this a bad practice or not?)

The problem I'm having is that the task executes fine - the results are shown as expected - but it appears as if it's run from the main thread (the UI freezes). What am I doing wrong? And what are the best practices for this?

InputUsername
  • 390
  • 1
  • 3
  • 12

0 Answers0