java - 通过按下 ANDROID 按钮加载 Xml

标签 java android

我已经发布了这个问题,但已经编辑了很多次,我想我会再次发布所有代码和 eclipse 包下载。

将 class extends Activity 更改为 class extends ListActivity 后,我在 eclipse 中没有遇到任何错误/问题。

如果有人发现我的问题可能会迫使应用程序关闭,请告诉我。谢谢!

ECLIPSE PROJECT DOWNLOAD

patriotsar.java

package com.patriotsar;




import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.patriotsar.XMLfunctions;


import android.app.ListActivity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;









public class patriosar extends ListActivity {

    private Button goButton;
    private Button quoteButton;

    String url = "http://www.patriotsar.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    Uri u = Uri.parse(url);
    Context context = this;



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



        goButton = (Button)findViewById(R.id.goButton);
        quoteButton = (Button)findViewById(R.id.quoteButton);

        goButton.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v){
                try {
                      // Start the activity
                        i.setData(u);
                      startActivity(i);
                    } catch (ActivityNotFoundException e) {
                      // Raise on activity not found
                      Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
                    }
                  } 
        });

        quoteButton.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v){
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


                String xml = XMLfunctions.getXML();
                Document doc = XMLfunctions.XMLfromString(xml);

                int numResults = XMLfunctions.numResults(doc);

                if((numResults <= 0)){
                    Toast.makeText(patriosar.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();  
                    finish();
                }

                NodeList nodes = doc.getElementsByTagName("result");

                for (int i = 0; i < nodes.getLength(); i++) {                           
                    HashMap<String, String> map = new HashMap<String, String>();    

                    Element e = (Element)nodes.item(i);
                    map.put("id", XMLfunctions.getValue(e, "id"));
                    map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
                    map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
                    mylist.add(map);            
                }       
//               
                ListAdapter adapter = new SimpleAdapter(patriosar.this, mylist , R.layout.main, 
                                new String[] { "name", "Score" }, 
                                new int[] { R.id.item_title, R.id.item_subtitle });

                setListAdapter(adapter);

                final ListView lv = getListView();
                lv.setTextFilterEnabled(true);  
                lv.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                        @SuppressWarnings("unchecked")
                        HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                        Toast.makeText(patriosar.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

                    }
                });



                }

         });

     }
    }

XMLfunctions.java

 package com.patriotsar;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;


public class XMLfunctions {

    public final static Document XMLfromString(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) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public static String getXML(){  
            String line = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

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

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }

            return line;

    }

    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

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

ListPlaceholder.xml:

    <ListView
        android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawSelectorOnTop="false" />

    <TextView
        android:id="@id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="No data"/>

</LinearLayout>

ma​​in.xml:

<?xml version="1.0" encoding="utf-8"?>

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bgimage2"> 
    >

<Button
android:id="@+id/quoteButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/start"
android:layout_x="80px"
android:layout_y="21px"
>
</Button>

<Button
android:id="@+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="@string/subscribe"
android:layout_x="80px"
android:layout_y="74px"
>
</Button>

<TextView
  android:id="@+id/textview"
  android:layout_width="300px"
  android:layout_height="fill_parent"
  android:text="@string/intro"
  android:layout_y="300px"
  android:layout_x="20px"
  android:textColor="#ffffff"
  />

  <TextView  
    android:id="@+id/item_title"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp" />
    <TextView  
    android:id="@+id/item_subtitle"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />
</AbsoluteLayout>

Android list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.patriotsar"
      android:versionCode="1"
      android:versionName="1.0">
 <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".patriosar"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

    <uses-permission android:name="android.permission.INTERNET" />

</manifest>

最佳答案

您正在扩展ListActivity。您在 setContentView() 中使用的布局需要有一个 ID 为 @android:id/listListView

编辑

此外,AbsoluteLayout 已被弃用。你不应该使用它们。但是,这不会导致您的应用强制关闭。

关于java - 通过按下 ANDROID 按钮加载 Xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6260415/

相关文章:

java - Jenkins - 如何将覆盖率报告发布到 github

android - Python:解压android备份?

java - 比较时间 : Check if a given time is within a certain amount of time of the another

Java 音频输入 lightorgran

java - 如果字符串包含两个带有 IgnoreCase 的单词之一

java - 有什么方法可以创建一个通用列表,在其中添加类型和子类型?

android - Xamarin Android 源 - 构建错误

java - onOptionsItemSelected() 方法未在 Fragment 上调用

java - ImageView 中的背景图片导致崩溃

java - JDO 枚举实现接口(interface)