2014-05-20 30 views
-1

我用這個連接到互聯網retrive從互聯網上的數據和檢索頁面的源代碼,很乾脆:無法在Android中

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_update_library); 
    String data = ""; 

    if(!isNetworkAvailable()){ 
     TextView tv = (TextView) findViewById(R.id.placeholder); 
     tv.setText("No Connection!!!"); 
     return; 
    } 

    try{ 
     URL url = null; 
     url = new URL("http://google.com"); 
     URLConnection conn = url.openConnection(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     String line = ""; 
     while((line = reader.readLine()) != null){ 
      data += line; 
     } 
     TextView tv = (TextView) findViewById(R.id.placeholder); 
     tv.setText(data); 
    }catch(Exception e){ 
     TextView tv = (TextView) findViewById(R.id.placeholder); 
     tv.setText("error : "+e.toString()); 
    } 
} 

,但數據不會從互聯網上回來。 有什麼問題?

+0

我是一個線程操作系統的asynctask。沒有網絡操作的UI線程 – Raghunandan

+0

你試過調試你的應用程序? – nikis

+0

@Raghunandan,主線程上無法連接互聯網嗎?我在教程中看到了它! – ConductedClever

回答

0

您需要將您的代碼從互聯網中檢索數據放在後臺任務中,以便在服務或AsyncTask中執行。

0

嘗試下面的代碼: -

TextView tv = (TextView) findViewById(R.id.placeholder); 
if(!isNetworkAvailable()){ 

    tv.setText("No Connection!!!"); 
    new ChangePasswordAsyncTask().execute(); 
    return; 
} 


private class ConnectToServer extends AsyncTask<String, String, String> 
{ 
    private String data; 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... params) 
    { 

     try 
     { 
      // do stuff from server 
        URL url = null; 
        url = new URL("http://google.com"); 
       URLConnection conn = url.openConnection(); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        String line = ""; 
       while((line = reader.readLine()) != null){ 
        data += line; 
       } 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return data; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) 
    { 
     // TODO Auto-generated method stub 
     super.onProgressUpdate(values); 
    } 

    @Override 
    protected void onPostExecute(String result) 
    { 
     super.onPostExecute(result); 
     // String jData = ""; 
     try 
     { 
      // set UI on this method 

       tv.setText(data); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      // Toast.makeText(context, jMessage, Toast.LENGTH_LONG).show(); 
     } 
    } 
} 
+0

它說,通過ID查找視圖不能用於異步任務! – ConductedClever

+0

立即嘗試更新代碼 – duggu

+0

我無法將您的代碼添加到我的項目中!連接到服務器的 – ConductedClever

0

你是否有明顯的權限來訪問互聯網?

+0

此答案是否有用? – Gunaseelan

+0

是的,我有權訪問互聯網。 – ConductedClever