我对android studio很新,并且有一个我似乎无法解决的问题。我正在使用for循环从网站解析一些XML来获取每个元素。我的问题是如何通过for循环在第一次迭代中暂停它,以便它不会继续到下一个迭代直到单击此按钮?
这是我的for循环:
try {
URL url = new URL("http://www.website.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("patient_order");
/** Assign textview array length by arraylist size */
patientName = new TextView[nodeList.getLength()];
patientID = new TextView[nodeList.getLength()];
medicine = new TextView[nodeList.getLength()];
dosage = new TextView[nodeList.getLength()];
refillsRemaining = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
patientName[i] = new TextView(this);
patientID[i] = new TextView(this);
medicine[i] = new TextView(this);
dosage[i] = new TextView(this);
refillsRemaining[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("patientName");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
patientName[i].setText("Patient: "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("patientID");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
patientID[i].setText("ID: "
+ ((Node) websiteList.item(0)).getNodeValue());
NodeList medicineList = fstElmnt.getElementsByTagName("medicine");
Element medicineElement = (Element) medicineList.item(0);
medicineList = medicineElement.getChildNodes();
medicine[i].setText("RX: "
+ ((Node) medicineList.item(0)).getNodeValue());
NodeList dosageList = fstElmnt.getElementsByTagName("dosage");
Element dosageElement = (Element) dosageList.item(0);
dosageList = dosageElement.getChildNodes();
dosage[i].setText("Dosage: "
+ ((Node) dosageList.item(0)).getNodeValue());
NodeList refillsList = fstElmnt.getElementsByTagName("refillsRemaining");
Element refillsElement = (Element) refillsList.item(0);
refillsList = refillsElement.getChildNodes();
refillsRemaining[i].setText("Remaining: "
+ ((Node) refillsList.item(0)).getNodeValue());
layout.addView(patientName[i]);
layout.addView(patientID[i]);
layout.addView(medicine[i]);
layout.addView(dosage[i]);
layout.addView(refillsRemaining[i]);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
//What is going to happen to make the for loop continue
}
});
}//end for
} //end try
答案 0 :(得分:0)
你永远不想暂停你的UI线程,所以创建一个新的线程来执行你的for循环。这个链接http://developer.android.com/training/multiple-threads/communicate-ui.html应该说明你的主UI线程之间的通信的一些选项(不能是不惜一切代价堵塞)和你的副线做实际的工作。您的主UI线程忙于保持屏幕活动和响应,因此暂停它通常是禁止的。
答案 1 :(得分:0)
您可以使用此答案中的方法:How to Pause and Resume a Thread in Java from another Thread。但它在你的情况下不起作用
<强>由于强>