繁体   English   中英

在ListView中填充ArrayList

[英]Populate ArrayList in ListView

我正在尝试使用ArrayList中的字符串数组填充一个简单的listview。 每次我尝试尽管它强制关闭。 我知道我在Logcat中看到了数组中正确的字符串。 我似乎无法弄清楚为什么要强制关闭。 也许我忘记了ArrayAdapter中的某些内容(对我来说似乎正确),或者我将填充方法放在错误的位置...有人可以帮我这个忙吗?

public class SchedLayout extends Activity {

public ArrayList<String> titleArray;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sched_layout_layout);

    new doParse().execute();
}

private class doParse extends AsyncTask<Void, Void, Void> {
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/directory/");
    File file = new File(dir, "file.html");

    @Override
    protected Void doInBackground(Void... params) {
        try {
            FileInputStream input = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    input, "UTF-8"));
            String line;
            titleArray = new ArrayList<String>();
            while ((line = br.readLine()) != null) {
                String html = line;
                Document doc = Jsoup.parse(html);
                Elements rels = doc.select("a[rel]");
                for (Element title : rels) {
                    String exclude = "Follow";
                    if (title.attr("title").contains(exclude)) {
                        continue;
                    }
                    titleArray.add(title.attr("title"));
                    // Log.v("", title.attr("title"));  <--works
                }
            }
            br.close();
            input.close();
            populate(titleArray);  <--does not work
        } catch (FileNotFoundException e) {
            //Never happens
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void populate(ArrayList<String> array) {
        ListView showList = (ListView) findViewById(R.id.listView1);
        ArrayAdapter<String> shows = new ArrayAdapter<String>(
                getApplicationContext(),
                android.R.layout.simple_list_item_1, array);
        showList.setAdapter(shows);
    }
}

}

将您的populate调用移至onPostExecute 您无法在doInBackground或任何与用户界面相关的界面中修改ListView

@Override
protected void onPostExecute(Void v) {
    populate(titleArray);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM