11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android Fragmentで非同期処理

Last updated at Posted at 2014-10-23

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);
    }
}
11
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?