2012-10-12 79 views
1

我使用自定義適配器和AsyncTask來讀取數據並將其放入列表視圖。但它不起作用。爲什麼我無法從互聯網加載數據到列表視圖

Thread t; 
int res; 
ArrayList<mLink> values; 
AdapterLink adapter; 
ListView lv; 
String title; 
InputStream is; 
private ReadXML readXML; 
TextView status; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    status = (TextView)findViewById(R.id.textView1); 
    lv = (ListView)findViewById(R.id.lView); 
    values = new ArrayList<mLink>();  
    readXML = new ReadXML(getApplicationContext()); 
    load(); 
} 

這是AsyncTask,但我認爲它不對?

private class DownloadWebpageText extends AsyncTask<String,integer,InputStream> { 
    protected InputStream doInBackground(String... urls) { 

     return connectT3H(urls[0]); 

    } 
    // onPostExecute displays the results of the AsyncTask. 
    protected void onPostExecute(InputStream result) { 
     values = readXML.read(result); 
     status.setText("Connected"); 
     Log.d("Http code", "adapter " + adapter.getCount()); 
    } 
} 

這個有趣的負荷,並連接

public void load(){ 
    String stringUrl = "http://vnexpress.net/rss/gl/trang-chu.rss"; 
    ConnectivityManager connMgr = (ConnectivityManager) 
     getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     new DownloadWebpageText().execute(stringUrl); 
    } else { 
     status.setText("No network connection available."); 
    } 
    adapter = new AdapterLink(getApplicationContext(), R.layout.item_layout, values); 
    lv.setAdapter(adapter); 
} 


public InputStream connectT3H(String mURL){ 

    int responseCode = 0; 

    InputStream in = null; 
    try { 
     URL url = new URL(mURL); 

     URLConnection connection = url.openConnection(); 

     HttpURLConnection httpURLConnection = (HttpURLConnection)connection; 

     responseCode = httpURLConnection.getResponseCode(); 

     if (responseCode == HttpURLConnection.HTTP_OK){ 
      in = httpURLConnection.getInputStream(); 
     } 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return in; 
} 

此代碼不是錯誤,但它不顯示數據爲列表視圖

+0

這是我們閱讀的很多代碼。 –

+0

你是否收到任何異常。如果是,那麼在這裏發佈logcat報告。 – Praveenkumar

+0

我沒有得到任何異常。但它不會加載我的佈局中的任何東西 – Zip

回答

0
new DownloadWebpageText().execute(stringUrl) 

這是你的問題。 函數doInBackground返回您的輸入流。將此輸入流保存到一個變量中,並將其傳遞到適配器中

+0

我已經保存了它,但它不起作用 – Zip

+0

請提及您保存它的代碼! – Ashwani

+0

我不保存它,我只是從互聯網上讀取它並將其加載到ListView中。 – Zip

相關問題