2013-08-25 89 views
0

我试图从Web获取XML数据并将这些数据显示到ListView中。但是当我运行该项目时出现了问题。你能帮我解决这个问题吗?谢谢。Android - 从网络获取XML

XMLParser.java

public class XMLParser extends Activity { 
public String getXmlFromUrl(String url) { 
    String xml = null; 

    try { 
     new Thread(new Runnable() { 
      public void run() { 
       try { 
        URL uri=new URL("http://api.androidhive.info/pizza/?format=xml"); 
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); 
        conn.setRequestMethod("GET"); 
        conn.setDoInput(true); 
        conn.connect();  

        System.out.println("done"); 
       } 
       catch(Exception e) { 
        e.printStackTrace(); 
       } 
      } 

     }).start(); 

//readfilethread.start(); 



     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     System.out.println("here"); 

     // HttpResponse httpResponse = httpClient.execute(httpPost); 
     //HttpEntity httpEntity = httpResponse.getEntity(); 
     //xml = EntityUtils.toString(httpEntity); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    // return XML 
    return xml; 

} 

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 DOM 
     return doc; 
} 

public String getValue(Element item, String str) {  
    NodeList n = item.getElementsByTagName(str);   
    return this.getElementValue(n.item(0)); 
} 

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 ""; 
    } 

AndroidXMLParsingActivity.java

public class AndroidXMLParsingActivity extends ListActivity { 


// All static variables.. 

static final String URL = "http://api.androidhive.info/pizza/?format=xml"; 
// XML node keys 
    static final String KEY_ITEM = "item"; // parent node 
    static final String KEY_ID = "id"; 
    static final String KEY_NAME = "name"; 
    static final String KEY_COST = "cost"; 
    static final String KEY_DESC = "description"; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 




     // -> menuItems 
     ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); 




     XMLParser parser = new XMLParser(); 
     String xml = parser.getXmlFromUrl(URL); // getting XML 
     Document doc = parser.getDomElement(xml); // getting DOM element 

     NodeList nl = doc.getElementsByTagName(KEY_ITEM); 

     // looping through all item nodes <item> 
     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_NAME, parser.getValue(e, KEY_NAME)); 
      map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST)); 
      map.put(KEY_DESC, parser.getValue(e, KEY_DESC)); 


      // adding HashList to ArrayList 
      menuItems.add(map); 
     } 


     // 2. Adding menuItems to ListView 
     ListAdapter adapter = new SimpleAdapter(this, menuItems, 
       R.layout.list_item, 
       new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] { 
         R.id.name, R.id.description, R.id.cost }); 
     setListAdapter(adapter); 

     // selecting single ListView item 
     android.widget.ListView lv = getListView(); 

     // listening to single list item click 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // getting values from selected ListItem 
       String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
       String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString(); 
       String description = ((TextView) view.findViewById(R.id.description)).getText().toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), SingleListItem.class); 
       in.putExtra(KEY_NAME, name); 
       in.putExtra(KEY_COST, cost); 
       in.putExtra(KEY_DESC, description); 
       startActivity(in); 





      } 
     }); 


    } 
} 

'

logcat的部分

08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main 

08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 

08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 

08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.app.ActivityThread.access$600(ActivityThread.java:141) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.os.Handler.dispatchMessage(Handler.java:99) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.os.Looper.loop(Looper.java:137) 

08-25 08:34:10.211: E/AndroidRuntime(1700):  at android.app.ActivityThread.main(ActivityThread.java:5039) 

.... 

08-25 08:34:10.341: I/System.out(1700): done 
+0

发布堆栈跟踪 – Raghunandan

+1

什么是错误?发布你的logcat跟踪 – Rahul

+0

你正在得到nullpointerexception指示导致相同并发布完整堆栈跟踪的行。 – Raghunandan

回答

0

试试这个代码...

import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 

import android.os.AsyncTask; 
import android.os.Build; 
import android.os.Bundle; 
import android.annotation.TargetApi; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

public class NetActivity extends Activity { 


    String url = "http://api.androidhive.info/pizza/?format=xml"; 


    // Progress dialog 
    ProgressDialog pDialog; 

    ArrayList<String> title; 
    ArrayList<String> description; 
    ArrayList<String> id; 
    ArrayList<String> cost; 

    ItemAdapter adapter1; 

    ListView list; 

    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_net); 

     list = (ListView) findViewById(R.id.list); 
     title = new ArrayList<String>(); 
     description = new ArrayList<String>(); 
     id = new ArrayList<String>(); 
     cost = new ArrayList<String>(); 


     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
      new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null}); 
     else 
      new XmlParsing(url).execute(new String[]{null}); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    public class XmlParsing extends AsyncTask<String, Void, String> { 

     // variables passed in: 
     String urls; 
     // constructor 
     public XmlParsing(String urls) { 
      this.urls = urls; 
     } 

     @Override 
     protected void onPreExecute() { 
      pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true); 
     } 


     @Override 
     protected String doInBackground(String... params) { 
      // TODO Auto-generated method stub 

      URL url; 
      try { 

       url = new URL(urls); 
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
       DocumentBuilder db = dbf.newDocumentBuilder(); 
       Document doc = db.parse(new InputSource(url.openStream())); 

       doc.getDocumentElement().normalize(); 

       NodeList nodeList = doc.getElementsByTagName("item"); 

       for (int i = 0; i < nodeList.getLength(); i++) { 

        Node node = nodeList.item(i);  

        Element fstElmnt = (Element) node; 
        NodeList nameList = fstElmnt.getElementsByTagName("name"); 
        Element nameElement = (Element) nameList.item(0); 
        nameList = nameElement.getChildNodes(); 
        title.add(""+ ((Node) nameList.item(0)).getNodeValue()); 

        System.out.println("name : "+((Node) nameList.item(0)).getNodeValue()); 


        Element fstElmnt1 = (Element) node; 
        NodeList nameList1 = fstElmnt1.getElementsByTagName("id"); 
        Element nameElement1 = (Element) nameList1.item(0); 
        nameList1 = nameElement1.getChildNodes(); 
        description.add(""+ ((Node) nameList1.item(0)).getNodeValue()); 

        System.out.println("id : "+ ((Node) nameList1.item(0)).getNodeValue()); 

        Element fstElmnt2 = (Element) node; 
        NodeList nameList2 = fstElmnt2.getElementsByTagName("cost"); 
        Element nameElement2 = (Element) nameList2.item(0); 
        nameList2 = nameElement2.getChildNodes(); 
        id.add(""+ ((Node) nameList2.item(0)).getNodeValue()); 

        System.out.println("cost : "+ ((Node) nameList2.item(0)).getNodeValue()); 

        Element fstElmnt3 = (Element) node; 
        NodeList nameList3 = fstElmnt3.getElementsByTagName("description"); 
        Element nameElement3 = (Element) nameList3.item(0); 
        nameList3 = nameElement3.getChildNodes(); 
        cost.add(""+ ((Node) nameList3.item(0)).getNodeValue()); 

        System.out.println("description : "+ ((Node) nameList3.item(0)).getNodeValue()); 

       } 

      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (ParserConfigurationException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (SAXException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      // Now we have your JSONObject, play around with it. 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 

      adapter1 = new ItemAdapter(this); 
      list.setAdapter(adapter1); 

     } 

    } 


class ItemAdapter extends BaseAdapter { 

     final LayoutInflater mInflater; 

     private class ViewHolder { 
      public TextView title_text; 
      public TextView des_text; 
      public TextView id_text; 
      public TextView cost_text; 
     } 

     public ItemAdapter(XmlParsing xmlParsing) { 
      // TODO Auto-generated constructor stub 
      super(); 
      mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
     } 

     //@Override 
     public int getCount() { 
      return title.size(); 
     } 

     //@Override 
     public Object getItem(int position) { 
      return position; 
     } 

     //@Override 
     public long getItemId(int position) { 
      return position; 
     } 

     //@Override 
     public View getView(final int position, View convertView, ViewGroup parent) { 
      View view = convertView; 
      final ViewHolder holder; 
      if (convertView == null) { 
       view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false); 
       holder = new ViewHolder(); 
       holder.title_text = (TextView) view.findViewById(R.id.title_text); 
       holder.des_text = (TextView) view.findViewById(R.id.des_text); 
       holder.id_text = (TextView) view.findViewById(R.id.id_text); 
       holder.cost_text = (TextView) view.findViewById(R.id.cost_text); 

       view.setTag(holder); 
      } else { 
       holder = (ViewHolder) view.getTag(); 
      } 

      holder.title_text.setText(""+title.get(position)); 


      holder.des_text.setText(""+description.get(position)); 
      holder.id_text.setText(""+id.get(position)); 
      holder.cost_text.setText(""+cost.get(position)); 

     return view; 
     } 
    } 
} 
+1

op的代码有什么问题? – Raghunandan