gpt4 book ai didi

java - 在 ListView 中填充 ArrayList

转载 作者:行者123 更新时间:2023-12-01 18:33:56 26 4
gpt4 key购买 nike

我正在尝试使用 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 或任何与 UI 相关的内容。

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

关于java - 在 ListView 中填充 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com