gpt4 book ai didi

Android AlertDialog 问题

转载 作者:行者123 更新时间:2023-11-30 04:03:19 24 4
gpt4 key购买 nike

我想让我的应用程序在 Http Response 等于 NULL 时显示一个对话框。但无法找到一种方法来做到这一点。我已经在我的代码中标记了它。谁能告诉我它是怎么做到的?以下是我的代码和我的尝试。

public class XMLParser {
private Activity activity = null;
// constructor
public XMLParser(Activity act) {
activity = act;
}

/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;

try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);

if (httpResponse == null) {

AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("No Response from Server ")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}

});
AlertDialog alert = builder.create();
alert.show();

}
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}

/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {

DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);

} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}

return doc;
}

/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}

/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}

最佳答案

初始化AlertDialog 对象时需要Activity 上下文。因此,按如下方式稍微更改您的类文件:

private Activity activity = null;

public XMLParser(Activity act) {
activity = act;
}

稍后在使用 AlertDialog 时,将其初始化如下:

AlertDialog.Builder builder = new AlertDialog.Builder(activity);

关于Android AlertDialog 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129332/

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