在开发Hello World背后的Android应用程序时,我是初学者!所以我真的需要有人告诉我我的应用程序有什么问题。我的应用程序非常简单,用户在editText
中输入问题并按下按钮,然后应用程序从Yahoo Answers API
检索信息。但当我按下按钮时,我得到的是TextView
中的“错误”消息。我真的需要另一只眼睛来看我的代码并告诉我出了什么问题。我的模拟器正在运行android 4.2.2。我不知道它的url是否会导致显示“错误”消息,或者是否是eclipse中的某些内容或我的代码中的内容。
有人请帮助!!
主要活动
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WhatsYourQuestion extends Activity implements OnClickListener {
static final String baseURL = "http://answer.yahooapis.com/AnswerService/V1/questionSearh?appid=example&query=";
EditText et;
TextView answer;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
answer = (TextView) findViewById(R.id.stockAnswerOuput);
Button myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String a = et.getText().toString();
StringBuilder URL = new StringBuilder(baseURL);
URL.append(a + "");
String fullUrl = URL.toString();
try{
URL website = new URL(fullUrl);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLProperties doingWork = new HandlingXMLProperties();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
String information = doingWork.getInformation();
et.setText(information);
}catch (Exception e){
et.setText("error");
XMLCollectedData类
public class XMLCollectedData {
private int answer = 0;
public void setAnswer(int a){
answer = a;
}
public String dataToString(){
return "Here is your answer" + answer;
}
处理xml属性类
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class HandlingXMLProperties extends DefaultHandler{
XMLCollectedData info = new XMLCollectedData();
public String getInformation() {
return info.dataToString();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
if(localName.equals("ChosenAnswer")){
String a = attributes.getValue("type");
int answer = Integer.parseInt(a);
info.setAnswer(answer);
}
我还需要知道我需要使用哪种santax,所以我可以定义qName。有人帮助