我有一个xml解析器类,如果我没有连接到互联网,它会崩溃。无论如何,我可以让班级去布局说,"没有连接"或者当连接不存在时类似的东西。感谢
Xml Parser
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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));
}
}
使用解析器的活动
public class CustomizedListView extends Fragment { // All static variables
static final String URL = "http://graffiti.hostoi.com/00Graffiti00/lists/00main00.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static final String KEY_LINK = "key";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news, container, false);
songsList = new ArrayList<HashMap<String, String>>();
list=(ListView) rootView.findViewById(R.id.list);
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), Article.class);
new Bundle();
intent.putExtra( "b", songsList.get(position).get(KEY_LINK));
startActivity(intent);
}
});
return rootView;
}
class RetrieveXML extends AsyncTask<String, Void, String> {
private Exception exception;
XMLParser parser = new XMLParser();
protected String doInBackground(String... urls) {
try {
return parser.getXmlFromUrl(urls[0]);
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String xml) {
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_ID));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
}
}
答案 0 :(得分:1)
试试这个..
在包中添加以下类
<强> Utils.java 强>
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
public class Utils {
public static boolean connectivity(Context c) {
if(c != null)
{
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
}
else
{
Log.v("utils--", "null");
return false;
}
}
}
在调用RetrieveXML
AsyncTask 之前,请使用如下代码。
if(Utils.connectivity(getActivity()))
{
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
}
else
{
Toast.makeText(getActivity(), "Please connect to working internet connection.", Toast.LENGTH_SHORT).show();
}