Java 用ANDROID按钮加载Xml
我已经发布了这期文章,但是已经编辑了很多次了,我想我会再次发布所有的代码和eclipse包下载 在我将class extends活动更改为class extends ListActivity之后,eclipse中没有出现任何错误/问题 如果有人看到我的问题,可能会迫使应用程序关闭,请让我知道。谢谢 patriotsar.javaJava 用ANDROID按钮加载Xml,java,android,Java,Android,我已经发布了这期文章,但是已经编辑了很多次了,我想我会再次发布所有的代码和eclipse包下载 在我将class extends活动更改为class extends ListActivity之后,eclipse中没有出现任何错误/问题 如果有人看到我的问题,可能会迫使应用程序关闭,请让我知道。谢谢 patriotsar.java package com.patriotsar; import java.util.ArrayList; import java.util.HashMap;
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();
}
});
}
});
}
}
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));
}
}
package com.patriotsar;
导入java.util.ArrayList;
导入java.util.HashMap;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.NodeList;
导入com.patriotsar.xml函数;
导入android.app.ListActivity;
导入android.content.ActivityNotFoundException;
导入android.content.Context;
导入android.content.Intent;
导入android.net.Uri;
导入android.os.Bundle;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.AdapterView;
导入android.widget.Button;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.Toast;
导入android.widget.AdapterView.OnItemClickListener;
公共类patriosar扩展了ListActivity{
私人按钮按钮;
私人按钮quoteButton;
字符串url=”http://www.patriotsar.com";
意向i=新意向(意向.行动\视图);
uriu=Uri.parse(url);
上下文=这个;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton=(按钮)findViewById(R.id.goButton);
quoteButton=(按钮)findViewById(R.id.quoteButton);
goButton.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
试一试{
//开始活动
i、 setData(u);
星触觉(i);
}捕获(ActivityNotFounde异常){
//未找到对活动的提升
Toast.makeText(上下文,“未找到浏览器”,Toast.LENGTH\u SHORT);
}
}
});
quoteButton.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
ArrayList mylist=新的ArrayList();
字符串xml=XMLfunctions.getXML();
Document doc=XMLfunctions.XMLfromString(xml);
int numResults=XMLfunctions.numResults(doc);
如果((numResults)
Android清单文件:
<?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/list
的ListView
编辑
另外,
AbsoluteLayout
s已被弃用。您不应该使用它们。但是,这并不会导致您的应用程序强制关闭。我刚刚看到在调试模式中提到id/list。谢谢,这很有效!我是android开发的初学者。您能给我一个想法,或者让我了解如何更改背景(新布局)的其他资源吗当单击XML按钮时?完全不同?没有ListView
?我个人不喜欢扩展ListActivity
,因为我觉得这有点限制。您可以在这里找到在活动中使用ListView
的示例代码:。然后,您可以通过调用setContentView()自由更改布局
使用不同的布局文件。再次感谢,我将查看链接。
<?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>
<?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>