S
S
sur-pavel2021-07-20 14:56:33
Java
sur-pavel, 2021-07-20 14:56:33

How to pass string from AssyncTask to method?

Good day everyone :)
In an android application using the Tabbed activity template, I added code in the model for searching in Google, which requires asynchronous execution

public class PageViewModel extends ViewModel {

    private MutableLiveData<Integer> mIndex = new MutableLiveData<>();
    private LiveData<String> mText = Transformations.map(mIndex, new Function<Integer, String>() {
        @Override
        public String apply(Integer input) {
           
           new AsyncSearch().execute("Поисковое слово", "10");
            return ; // что возвратить???
        }
    });

    class AsyncSearch extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... arg) {

            try {
                return GoogleSearchJava.Search(arg[0], arg[1]);

            } catch (IOException e) {
                e.printStackTrace();
                return e.getMessage() + "\n" + e.getStackTrace();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //что здесь написать???
        }
    }
}


How to get string from onPostExecute() to apply()?

GoogleSearchJava
public class GoogleSearchJava {

    public static final String GOOGLE_SEARCH_URL = "https://www.google.com/search";

    public static String Search(String searchTerm, String num) throws IOException {

        String searchURL = GOOGLE_SEARCH_URL + "?q=" + searchTerm + "&num=" + num;
        //without proper User-Agent, we will get 403 error
        Document doc = Jsoup.connect(searchURL).userAgent("Mozilla/5.0").get();

        //below will print HTML data, save it to a file and open in browser to compare
        //System.out.println(doc.html());

        //If google search results HTML change the <h3 class="r" to <h3 class="r1"
        //we need to change below accordingly
        Elements results = doc.select("h3.r > a");
        StringBuilder builder = new StringBuilder();
        for (Element result : results) {
            String linkHref = result.attr("href");
            String linkText = result.text();
            builder.append(linkHref + "\n" + linkText);
            System.out.println("Text::" + linkText + ", URL::" + linkHref.substring(6, linkHref.indexOf("&")));
        }
        return builder.toString();
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-07-20
@sur-pavel

What a poor API this thing has...
You need to write a custom LiveData that will go to the search, and also use switchMap instead of map.
Here it is available described.
And you don't have to use asynctasks to go online...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question