1

好的,我这几天一直在研究这个问题,并将我的问题缩小到我不认为它实际上是从 xml 文件中获取节点项来加载 URL 的事实。我正在使用 DOM 解析器来解析 xml 文件并加载到列表视图中。我正在尝试将每个项目的 URL 加载到自定义 webview 活动中,如果我硬编码一个 url 代替字符串 url,它可以完美地工作,如果我将字符串 url 放在那里它不会加载 URL 值。这是我正在使用的代码和类。谢谢您的帮助。

xml 解析器活动

 public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * 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);
        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 LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());

}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.list_row, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image


    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);

    // Setting all values in listview
    title.setText(song.get(CustomizedListView.KEY_TITLE));
    artist.setText(song.get(CustomizedListView.KEY_PUB_DATE));
    imageLoader.DisplayImage(song.get(CustomizedListView.KEY_LINK), thumb_image);
    return vi;
}
 }

主要活动

 public class CustomizedListView extends Activity {
// All static variables
static final String URL = "http://treymorgan.net/feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node 
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_PUB_DATE = "pubDate";
static final String KEY_LINK = "link";

ListView list;
LazyAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

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

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // 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_ITEM));
        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
        map.put(KEY_PUB_DATE, parser.getValue(e, KEY_PUB_DATE));
        map.put(KEY_LINK, parser.getValue(e, KEY_LINK));

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


    list=(ListView)findViewById(R.id.list);

    // Getting adapter by passing xml data ArrayList
    adapter=new LazyAdapter(this, songsList);        
    list.setAdapter(adapter);


    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Intent intent = new Intent(CustomizedListView.this, WebviewActivity.class);  
            Bundle b = new Bundle();
            intent.putExtra( "b", "KEY_LINK");
            startActivity(intent); 



             }

    });
}   
 }   

Webview Activity public class WebviewActivity extends Activity{ private WebView webview;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    Bundle b = getIntent().getExtras(); 
    String KEY_LINK = b.getString("b");

    webview = (WebView) findViewById(R.id.webView1);
    webview.setWebViewClient(new MyWebViewClient(this));
    webview.getSettings().setAppCacheEnabled(false);
    webview.getSettings().setBuiltInZoomControls(true);
    webview.setInitialScale(1);
    webview.loadUrl(KEY_LINK);



  }


       }

这是我正在解析的 XML 的示例项

 <item>
    <title>We’re Building a Feeding Center and Church in Honduras!</title>
    <link>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/</link>
    <comments>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/#comments</comments>
    <pubDate>Fri, 14 Sep 2012 15:47:15 +0000</pubDate>
    <dc:creator>Trey Morgan</dc:creator>
            <category><![CDATA[Honduras]]></category>

    <guid isPermaLink="false">http://treymorgan.net/?p=4640</guid>
    <description><![CDATA[Do you remember this post from two weeks ago about feeding kids in Buen Samaritano?  Marc Tindall needed $6000 to get the feeding center started (which will be used as a church too) &#8230; and this past Monday morning we presented him with the money. WOO HOO!  Thanks to all those who gave.]]></description>
 <wfw:commentRss>http://treymorgan.net/were-building-a-feeding-center-and-church-in-honduras/feed/</wfw:commentRss>
    <slash:comments>1</slash:comments>
<enclosure url="http://treymorgan.net/wp-content/uploads/2012/09/photo-101-224x300.jpg" length="2854" type="image/jpeg" />  
 </item>

感谢您对此提供的任何帮助

4

2 回答 2

0

传递给 webView 的 KEY_LINK url 的格式可能不正确。

尝试首先使用它正确编码:

String urlStr = KEY_LINK;
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

webview.loadUrl(url);
于 2012-10-06T03:29:37.447 回答
0

试试看:

对于从一个活动到另一个活动的传递字符串

第一项活动:

Intent indisplay = new Intent(FirstClass.this,SecondClass.class);
indisplay.putExtra("link",your link here);
startActivity(indisplay);

第二个活动:

 Intent indispaly = getIntent();
 String url = indispaly.getStringExtra("link");
    // your link from previous activity is stored into the url
于 2012-10-06T04:00:23.487 回答