【问题标题】:JSOUP Does not workJSOUP 不起作用
【发布时间】:2015-12-17 08:07:20
【问题描述】:

我正在尝试获取随机 Wikipedia 文章的标题并在列表视图中查看它们

http://en.wikipedia.org/wiki/Special:Random 此链接返回随机 Wiki 文章

这是我的代码:

final ListView listview = (ListView) findViewById(R.id.container);
    String []vals = new String[4];
    for(int i = 0 ; i < 4 ; i++)
    {
        try {
            Document doc = Jsoup.connect("http://en.wikipedia.org/wiki/Special:Random").get() ;
            vals[i] = doc.title();
        }catch(IOException e){}
    }
    final ArrayList<String> List = new ArrayList<>() ;
    for(int i = 0 ; i < vals.length ; i++)
        List.add(vals[i]);
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_expandable_list_item_1 , List) ;
    listview.setAdapter(adapter);

但是当我在模拟器上运行我的代码时,应用程序崩溃,有什么想法吗??

【问题讨论】:

  • 我真的不知道,只是崩溃!
  • 你看不到任何错误 /logcat 吗?
  • catch(IOException e){} 太糟糕了。为什么空的 catch 块?
  • 你需要在 AsyncTask 中运行它,否则你会得到一个 android.os.NetworkOnMainThreadException
  • “JSOUP 不起作用”——是的,根据经验,它确实起作用。如果没有,您需要证明它没有,并且您的代码没有显示此类证明。这里的问题不在于jsoup不起作用,而是你使用不当。

标签: java android web android-studio jsoup


【解决方案1】:

您正在从导致异常的 UI 线程发出网络请求

您需要在后台线程上进行网络传输。 就我个人而言,我为此使用 Androids AsyncTask 类,以便将 textView 中的文本设置为您需要执行此操作的互联网之外的内容

private class GetTextOverNetwork extends AsyncTask<String,String,String>{

     protected String doInBackGround()
    {
      // here you get the info off the internet 
    }

    protected void onPostExecute(String result){
     // here you update your UI
    }
}

将上述私有类添加到您的活动并修改您需要的变量 记住

1)你不能从主线程访问网络,所以在这种情况下你可以在 doInBackGround

2) 您无法从后台线程修改 UI,因此您可以在 onPostExcute 方法中进行修改

3) Asynctask 是 AsyncTask 的形式,所以它不必是

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多