2014-05-23 24 views
-1

這是應該從指定網站讀取文本的代碼,但變量「result」只是簡單地給我輸出。我無法獲得main(null)函數的運行。它只是無論何時何地調用應用程序而崩潰。 (正在調用MainActivity的onCreate())在Eclipse中讀取一個網頁android

public class ConvertUrlToString { 

     public void main(String[] args) { 

      try { 
       webPage = "http://www.albab.pk/albab_edu/mashal/dsms.aspx"; 
       URL url = new URL(webPage); 
       URLConnection urlConnection = url.openConnection(); 
       InputStream is = urlConnection.getInputStream(); 
       InputStreamReader isr = new InputStreamReader(is); 

       int numCharsRead; 
       char[] charArray = new char[1024]; 
       StringBuffer sb = new StringBuffer(); 
       while ((numCharsRead = isr.read(charArray)) > 0) { 
        sb.append(charArray, 0, numCharsRead); 
       } 
       result = sb.toString(); 

      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 

     SmsManager sms = SmsManager.getDefault(); 
     PendingIntent piSent = PendingIntent.getBroadcast(this, 0, new Intent("SMS_SENT"), 0); 
     PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0); 
     sms.sendTextMessage("+923018744545", null, "Hi There!", piSent, piDelivered); 
    } 

public void onReceive(Context arg0, Intent arg1) { 
       // TODO Auto-generated method stub 
       switch (getResultCode()) { 
       case Activity.RESULT_OK: 
        Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_GENERIC_FAILURE: 
        Toast.makeText(getBaseContext(), "Generic Failure", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NO_SERVICE: 
        Toast.makeText(getBaseContext(), "No Service", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_NULL_PDU: 
        Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show(); 
        break; 
       case SmsManager.RESULT_ERROR_RADIO_OFF: 
        Toast.makeText(getBaseContext(), "Radio Off", Toast.LENGTH_SHORT).show(); 
        break; 
       default: 
        break; 
       } 

      } 
+0

問題是我無法獲得ConvertURLToString.main(null)的運行。它只是崩潰的應用程序。任何人都可以幫助我瞭解在閱讀網頁內容的代碼中出現什麼錯誤? – user3668388

回答

0

你的代碼看起來很好,我測試了它。有用。請檢查您是否已給internet permission。添加到你的AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET" />

此外,既然你說「eclipse android」,我假設你正在通過模擬器嘗試它。在這種情況下,檢查你的機器是否在任何代理之後?如果是這樣,您還需要添加適當的系統屬性。

System.setProperty("http.proxyHost", "your host name/ip"); 
System.setProperty("http.proxyPort", "your host port"); 

當我說它的工作,我只是採取有關main()方法。當您致電PendingIntent.getBroadcast(this, 0, new Intent(result), 0);時,應確保在點擊之前設置結果值,即驗證在click事件之前是否調用main方法。