2013-08-20 49 views
0

當我打開應用程序時,我收到消息「應用程序停止」。可能是什麼原因?Android JSoup使應用程序崩潰

主類:

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 

* I中的AsyncTask添加)罐子庫

+0

張貼您的錯誤。 –

回答

0

移動getHtmlCode(。你不應該在onCreate()方法或主線程上進行網絡操作。所以把你的代碼移到AsyncTask。並可以更新AsyncTask本身的UI。

0

您需要對Android清單文件具有以下權限。

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

添加上述權限後,需要將方法getHtmlCode()內的代碼移動到異步任務或線程中。之後,你很好走。