Android Fragmentで非同期処理


jsoupで楽できた!と思っていたのも束の間。
非同期にしてあげないといけなくなったらしい。
処理の書き方としてはjsoupを使わなかったときと同じようなのだけど、それはActivityに処理を書いてたんです。
(たぶんですが、Activityに書いたほうがいい処理なんじゃないかと思います)

Fragmentで処理しようとしたら、onPostExecuteでfindViewByIdができなくてひとしきり悩みました。
とりあえず、FragmentのonCreateViewの変数rootViewを、Fragmentのクラスのメンバに(格上げ?)して、そのまんま使い回せばエラーなしで動きました。

itemDetailFragment
        public View rootView;
onCreateView
        rootView = inflater.inflate(R.layout.fragment_item_detail, container, false);
        new getData().execute();
private class getData extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void...voids) {

        StringBuilder ret = new StringBuilder();
        try {
            Document doc = Jsoup.connect("http://example.jp/list.html").get();
            Elements elm = doc.select("a[href]").select("a[target=main]");
            for (Element el : elm) {
                ret.append(String.format("%s: %s\n", el.text(), el.attr("abs:href")));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }
    @Override
    protected void onPostExecute(String result) {
         ((TextView)rootView.findViewById(R.id.item_detail)).setText(result);
    }
}