2011-07-13 39 views
1

我是一個新手在java中,並試圖android開發。下面的代碼生成了malformedURLException.can人幫我識別異常。 任何暗示將是非常有益的java.net.URL在Android ..新手問題

package com.example.helloandroid; 

import android.app.Activity; 
//import android.widget.TextView; 
import android.os.Bundle; 
import java.net.*; 
import java.io.*; 
import android.widget.TextView; 

public class HelloAndroid extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     TextView tv = new TextView(this); 
     String outdata = ""; 
     URL url_g = new URL("http://www.google.com/"); 
     URLConnection ukr = url_g.openConnection(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(ukr.getInputStream())); 
     String inputLine; 
     while ((inputLine = in.readLine()) != null) 
      outdata += inputLine; 
     in.close(); 
     tv.setText(outdata); 
     setContentView(tv); 
    } 
} 
+0

我覺得應該是'URL url_g =新的URL( 「://www.google.com/」);' – MByD

+0

你同另一個網址試過嗎? ?我看不到任何錯誤 – JAiro

+0

你的代碼在我的機器上成功運行,在我看來也很好(儘管你應該使用'StringBuilder'而不是'+ = String')。在尋求異常幫助時始終包含堆棧跟蹤,這可能對此有所幫助。 – LeffelMania

回答

6

這是因爲URL構造(新URL( 「http://www.google.com/」))拋出檢查異常,在這種情況下MalformedURLException的,這意味着你必須抓住它或者在你的方法中聲明它。

在onCreate方法中使用try/catch或throws子句。

的try/catch解決方案:

public void onCreate(Bundle savedInstanceState) { 
    ... 
    try { 
     URL url_g = new URL("http://www.google.com/"); 
    } catch(MalformedURLException e) { 
     //Do something with the exception. 
    } 
    ... 
} 

拋出的解決方案:

@Override 
public void onCreate(Bundle savedInstanceState) throws MalformedURLException { 
    ... 
    URL url_g = new URL("http://www.google.com/"); 
    ... 
} 

檢查這個關於異常的更多信息。

http://download.oracle.com/javase/tutorial/essential/exceptions/

1

那麼你需要在第一次使用try/catch方法來執行你的代碼。試試吧,讓c你有更多?