2013-07-25 37 views
2

我希望獲得此鏈接「」正常工作。 我想檢索RSS提要,並在文本視圖中顯示它,檢索RSS提要並在文本視圖中顯示

我試過了代碼,但似乎並沒有工作。 我想代碼有問題,但我不確定它出錯的地方。 我是新來的android。

我需要幫助。

謝謝。

這是我的代碼。

MainActivity.java

public class MainActivity extends Activity { 

TextView psi; 

class MyWeather{ 
    String title; 
String description; 


public String toString(){ 

return "\n- " 

    + "Condition: " + title + "\n" 
    + description +"\n"; 

} 
} 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    psi = (TextView)findViewById(R.id.psi); 


    new MyAsyncTask().execute(); 
} 


    public class MyAsyncTask extends AsyncTask<Void, Void, Void> { 
      ProgressDialog dialog; 
      MyWeather weatherResult; 

      @Override 
      protected void onPreExecute() { 
       // TODO Auto-generated method stub 
       dialog = new ProgressDialog(MainActivity.this); 
       dialog.setMessage("Please wait..."); 
       dialog.show(); 
       super.onPreExecute(); 
      } 

      @Override 
      protected Void doInBackground(Void... params) { 
       String weatherString = QueryYahooWeather(); 
       Document weatherDoc = convertStringToDocument(weatherString); 

       weatherResult = parseWeather(weatherDoc); 
       Document dest = null; 

       DocumentBuilderFactory dbFactory = 
        DocumentBuilderFactory.newInstance(); 
       DocumentBuilder parser; 

       try { 
       parser = dbFactory.newDocumentBuilder(); 
       dest = parser.parse(new ByteArrayInputStream(src.getBytes())); 
       } catch (ParserConfigurationException e1) { 
       e1.printStackTrace(); 
       Toast.makeText(MainActivity.this, 
        e1.toString(), Toast.LENGTH_LONG).show(); 
       } catch (SAXException e) { 
       e.printStackTrace(); 
       Toast.makeText(MainActivity.this, 
        e.toString(), Toast.LENGTH_LONG).show(); 
       } catch (IOException e) { 
       e.printStackTrace(); 
       Toast.makeText(MainActivity.this, 
        e.toString(), Toast.LENGTH_LONG).show(); 
       } 

       return dest; 
       } 

      private MyWeather parseWeather(Document weatherDoc) { 
       MyWeather myWeather = new MyWeather(); 

        //<description>Yahoo! Weather for New York, NY</description> 
        //myWeather.description = srcDoc.getElementsByTagName("description") 
        //.item(0) 
        //.getTextContent(); 


        Node locationNode = srcDoc.getElementsByTagName("item").item(0); 
        myWeather.title = locationNode.getAttributes() 
        .getNamedItem("title") 
        .getNodeValue() 
        .toString(); 
       myWeather.description = locationNode.getAttributes() 
        .getNamedItem("description") 
        .getNodeValue() 
        .toString(); 

        return myWeather; 
       } 

      } 

      } 

      private Document convertStringToDocument(String weatherString) { 
       // TODO Auto-generated method stub 
       return null; 
      } 

      private String QueryYahooWeather() { 
       // TODO Auto-generated method stub 
       String qResult = ""; 
        String queryString = "app2.nea.gov.sg/data/rss/nea_psi.xml"; 

        HttpClient httpClient = new DefaultHttpClient(); 
        HttpGet httpGet = new HttpGet(queryString); 

        try { 
         HttpEntity httpEntity = httpClient.execute(httpGet).getEntity(); 

         if (httpEntity != null){ 
         InputStream inputStream = httpEntity.getContent(); 
         Reader in = new InputStreamReader(inputStream); 
         BufferedReader bufferedreader = new BufferedReader(in); 
         StringBuilder stringBuilder = new StringBuilder(); 

         String stringReadLine = null; 

         while ((stringReadLine = bufferedreader.readLine()) != null) { 
         stringBuilder.append(stringReadLine + "\n"); 
         } 

         qResult = stringBuilder.toString(); 
         } 

       } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
       Toast.makeText(MainActivity.this, 
        e.toString(), Toast.LENGTH_LONG).show(); 
       } catch (IOException e) { 
       e.printStackTrace(); 
       Toast.makeText(MainActivity.this, 
        e.toString(), Toast.LENGTH_LONG).show(); 
       } 

        return qResult; 


       } 

      @Override 
      protected void onPostExecute(Void result) { 
       // TODO Auto-generated method stub 

       dialog.dismiss(); 
       psi.setText(weatherResult.toString()); 
       super.onPostExecute(result); 
      } 

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".MainActivity" > 





     <TextView 
      android:id="@+id/psi" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 


</LinearLayout> 
+0

使用線程加載從互聯網上的內容。它會幫助你http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html#concurrency_asynchtask –

+0

你的意思是, 我應該添加synctask – Febbie

+0

是的!如果你在android> = 3.0 –

回答

2

使用此代碼...!

import java.net.URL; 
import java.util.ArrayList; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

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 android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.text.Html; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

public class XMLParsingDOMExample extends Activity { 

    ArrayList<String> title; 
    ArrayList<String> description; 
    ItemAdapter adapter1; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

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

     try { 

      URL url = new URL(
        "http://app2.nea.gov.sg/data/rss/nea_psi.xml"); 
      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("title"); 
       Element nameElement = (Element) nameList.item(0); 
       nameList = nameElement.getChildNodes();   

       title.add(""+ ((Node) nameList.item(0)).getNodeValue()); 

       NodeList websiteList = fstElmnt.getElementsByTagName("description"); 
       Element websiteElement = (Element) websiteList.item(0); 
       websiteList = websiteElement.getChildNodes(); 

       description.add(""+ ((Node) websiteList.item(0)).getNodeValue());   

      } 
     } catch (Exception e) { 
      System.out.println("XML Pasing Excpetion = " + e); 
     } 

     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 ItemAdapter(Context context) { 
      // TODO Auto-generated constructor stub 
      super(); 
      mInflater = (LayoutInflater)context.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); 

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

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

      holder.des_text.setText(""+Html.fromHtml(description.get(position))); 

     return view; 
     } 
    } 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 


    <ListView 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
       > 

    </ListView> 
</LinearLayout> 

mainpage_listitem_activity.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    > 

      <TextView 
       android:id="@+id/title_text" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"  
       android:text="title" 
       android:layout_margin="5dp" 
       android:textSize="22dp" 
       android:textColor="#FFFFFF"/> 

      <TextView 
       android:id="@+id/des_text" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content"  
       android:gravity="center" 
       android:text="description " 
       android:layout_margin="5dp" 
       android:textSize="18dp" 
       android:textColor="#FFFFFF"/> 

</LinearLayout> 
+0

是否有可能不讓它視爲LISTVIEW? – Febbie

+0

你從listview中得到了這段代碼的標題和描述嗎? – Hariharan

+0

嗨,是的,我做到了。 我希望在文本視圖中,然後列出視圖 – Febbie

0

做一個AsyncTask這樣

public class MyAsyncTask extends AsyncTask<Void, Void, Void> { 
     ProgressDialog dialog; 
     MyWeather weatherResult; 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      dialog = new ProgressDialog(MainActivity.this); 
      dialog.setMessage("Please wait..."); 
      dialog.show(); 
      super.onPreExecute(); 
     } 

     @Override 
     protected Void doInBackground(Void... params) { 
      String weatherString = QueryYahooWeather(); 
      Document weatherDoc = convertStringToDocument(weatherString); 

      weatherResult = parseWeather(weatherDoc); 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 

      dialog.dismiss(); 
      psi.setText(weatherResult.toString()); 
      super.onPostExecute(result); 
     } 

    } 

,改變你的onCreate這樣

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    psi = (TextView)findViewById(R.id.psi); 


    new MyAsyncTask().execute(); 
} 

做到這一點

  • 顯示在onPreExecute
  • 進度對話框DO網絡的呼叫和doInBackground
  • 更新解析在onPostExecute如顯示的結果來看,駁回對話框
+0

添加或創建新的上課呢? – Febbie

+0

現在在同一班上做。 –

+0

我剛纔編輯了我的代碼, 你是這個意思嗎? 但有一些錯誤發生 – Febbie