android - 检索 RSS 提要并将其显示在 TextView 中

标签 android psi

我想让这个链接“”正常工作。 我想检索 RSS 提要并将其显示在 TextView 中,

我已经尝试过该代码,但似乎不起作用。 我猜代码有问题,但我不确定哪里出了问题。 我是 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>

最佳答案

使用此代码...!

    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>

关于android - 检索 RSS 提要并将其显示在 TextView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17848510/

相关文章:

android - 我应该在 Android 中为启动画面保留什么图像大小?

android - Android编译错误-transformJackWithJackForDebug

ms-project - 使用 CSOM 仅发布 1 个项目即可更新多个任务

mysql - 使用 INNER JOIN 函数插入值的 SQL 错误

project-server - 如何知道项目是否从 PSI checkout 或 checkin ?

android - SecurityException: 未能找到用户 0 的提供程序 null;在 ActiveAndroid 上 Android 8.0

android - LibGDX + gdx-freetype + BlueStacks

java - Android 尝试运行 unix 可执行文件 : syntax error: '__TEXT' unexpected