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;
}   

此代码不是错误,但不会将数据显示到列表视图中

4

1 回答 1

0
new DownloadWebpageText().execute(stringUrl) 

这是你的问题。该函数doInBackground返回您的输入流。将此输入流保存到变量中并将其传递给适配器

于 2012-10-12T04:44:51.680 回答