繁体   English   中英

Android JSoup使应用程序崩溃

[英]Android JSoup make the app crash

当我打开应用程序时,我收到消息“应用程序停止”。 可能是什么原因?

主班:

public class MainActivity extends Activity {

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // Always call super.onCreate() first.
        setContentView(R.layout.activity_main); // Then load the layout.

        // Find textView3 in layout and set it's text to HTML code.
        // There's no need to create a new TextView() here.
        TextView textView = (TextView) findViewById(R.id.textView1);
        textView.setText(getHtmlCode());
      }

      // Structure your code. If it's a larger block that does one thing,
      // extract it into a method.
      private String getHtmlCode() {
        try {
          Document doc = Jsoup.connect("http://www.example.com/").get();
          Element content = doc.select("a").first();
         // return content.text();
          return "kktt";
        } catch (IOException e) {
          Toast.makeText(this, "Failed to load HTML code",
              Toast.LENGTH_SHORT).show();
          return "kk";
        }
      }
    }

////Elements divs = doc.select("div#test");   //select all the content of the div tags with the id attribute set to test

*我将罐子添加到库中

将getHtmlCode()移到AsyncTask中。 您不应在onCreate()方法或Main线程上执行网络操作。 因此,将您的代码移至AsyncTask。 并可以在AsyncTask本身中更新UI。

您需要对Android清单文件具有以下权限。

<uses-permission android:name="android.permission.INTERNET" />

添加以上权限后,您需要将方法getHtmlCode()中的代码移动到异步任务或线程。 在那之后,你很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM