Java 应用程序仅适用于第一个输入,如果插入第二个输入,应用程序将崩溃

Java 应用程序仅适用于第一个输入,如果插入第二个输入,应用程序将崩溃,java,android,Java,Android,该应用程序按预期工作。输入股票符号,按下enter按钮,数据从yahoo webservice中提取并显示在屏幕上。但是,在显示第一个股票符号后,如果输入新的股票符号,应用程序将崩溃 MainActivity.java package com.example.quickstockinfo; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java

该应用程序按预期工作。输入股票符号,按下enter按钮,数据从yahoo webservice中提取并显示在屏幕上。但是,在显示第一个股票符号后,如果输入新的股票符号,应用程序将崩溃

MainActivity.java

package com.example.quickstockinfo;


import java.io.IOException; 
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

 import org.apache.http.HttpResponse;
 import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;



import android.app.Activity;  
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText stocksymbol;
String stocksymbolstring;

Button enterbutton;

TextView CompanyName;
TextView YearLow;
TextView YearHigh;
TextView DaysLow;
TextView DaysHigh;
TextView LastPrice;
TextView Change;
TextView DailyPriceRange;

// XML node keys
    static final String KEY_ITEM = "quote"; // parent node
    static final String KEY_NAME = "Name";
    static final String KEY_YEAR_LOW = "YearLow";
    static final String KEY_YEAR_HIGH = "YearHigh";
    static final String KEY_DAYS_LOW = "DaysLow";
    static final String KEY_DAYS_HIGH = "DaysHigh";
    static final String KEY_LAST_TRADE_PRICE = "LastTradePriceOnly";
    static final String KEY_CHANGE = "Change";
    static final String KEY_DAYS_RANGE = "DaysRange";

    // XML Data to Retrieve
    String name = "";
    String yearLow = "";
    String yearHigh = "";
    String daysLow = "";
    String daysHigh = "";
    String lastTradePriceOnly = "";
    String change = "";
    String daysRange = "";

    // Used to make the URL to call for XML data
    String yahooURLFirst = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22";
    String yahooURLSecond = "%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

    // NEW STUFF

    // Holds values pulled from the XML document using XmlPullParser
    String[][] xmlPullParserArray = {{"AverageDailyVolume", "0"}, {"Change", "0"}, {"DaysLow", "0"},
            {"DaysHigh", "0"}, {"YearLow", "0"}, {"YearHigh", "0"},
            {"MarketCapitalization", "0"}, {"LastTradePriceOnly", "0"}, {"DaysRange", "0"},
            {"Name", "0"}, {"Symbol", "0"}, {"Volume", "0"},
            {"StockExchange", "0"}};

    int parserArrayIncrement = 0;

    // END OF NEW STUFF

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    stocksymbol = (EditText)findViewById(R.id.stocksymbol);

    enterbutton = (Button)findViewById(R.id.enterbutton);

    CompanyName = (TextView)findViewById(R.id.stockName);
    YearLow = (TextView)findViewById(R.id.YearLow);
    YearHigh = (TextView)findViewById(R.id.YearHigh);
    DaysLow = (TextView)findViewById(R.id.DaysLow);
    DaysHigh = (TextView)findViewById(R.id.DaysHigh);
    LastPrice = (TextView)findViewById(R.id.LastPrice);
    Change = (TextView)findViewById(R.id.Change);
    DailyPriceRange = (TextView)findViewById(R.id.DailyPriceRange);

    enterbutton.setOnClickListener(enterbuttonlistener);


}

public OnClickListener enterbuttonlistener = new OnClickListener(){

    public void onClick(View v) {

        if(stocksymbol.getText().length() > 0){


            stocksymbolstring = stocksymbol.getText().toString();

            stocksymbol.setText(""); // Clear EditText box

            // Force the keyboard to close
            InputMethodManager imm = (InputMethodManager)getSystemService(
                      Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(stocksymbol.getWindowToken(), 0);
        } else {

            // Create an alert dialog box
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            // Set alert title 
            builder.setTitle("invalid stock symbol");

            // Set the value for the positive reaction from the user
            // You can also set a listener to call when it is pressed
            builder.setPositiveButton("ok", null);

            // The message
            builder.setMessage("missing stock symbol");

            // Create the alert dialog and display it
            AlertDialog theAlertDialog = builder.create();
            theAlertDialog.show();



        }// end else


        // Create the YQL query
        final String yqlURL = yahooURLFirst + stocksymbolstring + yahooURLSecond;

        new MyAsyncTask().execute(yqlURL);

    } //end onClick view v


}; //end button click event



private class MyAsyncTask extends AsyncTask<String, String, String>{

    // String... arg0 is the same as String[] args
    protected String doInBackground(String... args) {

        // NEW STUFF

        try{

            Log.d("test","In XmlPullParser");

            // It is recommended to use the XmlPullParser because
            // it is faster and requires less memory then the DOM API

            // XmlPullParserFactory provides you with the ability to 
            // create pull parsers that parse XML documents

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();

            // Parser supports XML namespaces
              factory.setNamespaceAware(true);

              // Provides the methods needed to parse XML documents
              XmlPullParser parser = factory.newPullParser(); 

              // InputStreamReader converts bytes of data into a stream
              // of characters

              parser.setInput(new InputStreamReader(getUrlData(args[0])));  

              // Passes the parser and the first tag in the XML document
              // for processing

              beginDocument(parser,"query");

              // Get the currently targeted event type, which starts
              // as START_DOCUMENT

              int eventType = parser.getEventType();

              do{

                // Cycles through elements in the XML document while
                // neither a start or end tag are found

                  nextElement(parser);

                  // Switch to the next element

                  parser.next();

                  // Get the current event type

                  eventType = parser.getEventType();

                  // Check if a value was found between 2 tags

                  if(eventType == XmlPullParser.TEXT){

                      // Get the text from between the tags

                      String valueFromXML = parser.getText();

                      // Store it in an array with the corresponding tag
                      // value

                      xmlPullParserArray[parserArrayIncrement++][1] = valueFromXML;

                  }

              } while (eventType != XmlPullParser.END_DOCUMENT) ;  

        }

        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  

        finally {
        }

        // END OF NEW STUFF

        return null;
    }

    // NEW STUFF

    public InputStream getUrlData(String url) throws URISyntaxException, 
    ClientProtocolException, IOException {

        // Used to get access to HTTP resources

        DefaultHttpClient client = new DefaultHttpClient();

        // Retrieves information from the URL

        HttpGet method = new HttpGet(new URI(url));

        // Gets a response from the client on whether the 
        // connection is stable

        HttpResponse res = client.execute(method);

        // An HTTPEntity may be returned using getEntity() which tells 
        // the system where the content is coming from

        return res.getEntity().getContent();
    }

    public final void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException
    {
        int type;

        // next() advances to the next element in the XML
        // document being a starting or ending tag, or a value
        // or the END_DOCUMENT

        while ((type=parser.next()) != parser.START_TAG
                       && type != parser.END_DOCUMENT) {
                ;
        }

        // Throw an error if a start tag isn't found

        if (type != parser.START_TAG) {
            throw new XmlPullParserException("No start tag found");
        }

        // Verify that the tag passed in is the first tag in the XML
        // document

        if (!parser.getName().equals(firstElementName)) {
                throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
                        ", expected " + firstElementName);
        }
    }

    public final void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException
    {
        int type;

        // Cycles through elements in the XML document while
        // neither a start or end tag are found

        while ((type=parser.next()) != parser.START_TAG
                       && type != parser.END_DOCUMENT) {
                ;
        }
    }

    // END OF NEW STUFF

    // Changes the values for a bunch of TextViews on the GUI
    protected void onPostExecute(String result){

        CompanyName.setText(xmlPullParserArray[9][1]);
        YearLow.setText("Year Low: " + xmlPullParserArray[4][1]);
        YearHigh.setText("Year High: " + xmlPullParserArray[5][1]);
        DaysLow.setText("Days Low: " + xmlPullParserArray[2][1]);
        DaysHigh.setText("Days High: " + xmlPullParserArray[3][1]);
        LastPrice.setText("Last Price: " + xmlPullParserArray[7][1]);
        Change.setText("Change: " + xmlPullParserArray[1][1]);
        DailyPriceRange.setText("Daily Price Range: " + xmlPullParserArray[8][1]);

    }

}

}
package com.example.quickstockinfo;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.URI;
导入java.net.URISyntaxException;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.xmlpull.v1.XmlPullParser;
导入org.xmlpull.v1.XmlPullParserException;
导入org.xmlpull.v1.XmlPullParserFactory;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.view.inputmethod.InputMethodManager;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TableRow;
导入android.widget.TextView;
公共类MainActivity扩展了活动{
编辑文本符号;
字符串stocksymbolstring;
按钮输入按钮;
TextView公司名称;
TextView YearLow;
文本视图年高;
TextView DaysLow;
TextView DaysHigh;
TextView最新价格;
文本视图更改;
文本视图每日价格范围;
//XML节点密钥
静态最终字符串KEY\u ITEM=“quote”;//父节点
静态最终字符串键\u NAME=“NAME”;
静态最终字符串键\u YEAR\u LOW=“YearLow”;
静态最终字符串键\u YEAR\u HIGH=“YearHigh”;
静态最终字符串键\u DAYS\u LOW=“DaysLow”;
静态最终字符串键\u DAYS\u HIGH=“DaysHigh”;
静态最终字符串键\u LAST\u TRADE\u PRICE=“LastTradePriceOnly”;
静态最终字符串键\u CHANGE=“CHANGE”;
静态最终字符串键\u DAYS\u RANGE=“DaysRange”;
//要检索的XML数据
字符串名称=”;
字符串yearLow=“”;
字符串yearHigh=“”;
字符串daysLow=“”;
字符串daysHigh=“”;
字符串lastTradePriceOnly=“”;
字符串更改=”;
字符串daysRange=“”;
//用于生成用于调用XML数据的URL
字符串yahooURLFirst=”http://query.yahooapis.com/v1/public/yql?q=select%20*%20来自%20yahoo.finance.quote%20,其中%20symbol%20位于%20(%22);
字符串yahooURLSecond=“%22)&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys”;
//新东西
//保存使用XmlPullParser从XML文档中提取的值
字符串[][]XmlPullParseRaray={{“AverageDailyVolume”,“0”},{“Change”,“0”},{“DaysLow”,“0”},
{“DaysHigh”,“0”},{“YearLow”,“0”},{“YearHigh”,“0”},
{“市值”、“0”}、{“LastTradePriceOnly”、“0”}、{“DaysRange”、“0”},
{“名称”,“0”},{“符号”,“0”},{“卷”,“0”},
{“证券交易所”,“0”};
int parserayrayincrement=0;
//新事物的终结
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stocksymbol=(EditText)findViewById(R.id.stocksymbol);
enterbutton=(按钮)findViewById(R.id.enterbutton);
CompanyName=(TextView)findViewById(R.id.stockName);
YearLow=(TextView)findViewById(R.id.YearLow);
YearHigh=(TextView)findViewById(R.id.YearHigh);
DaysLow=(TextView)findViewById(R.id.DaysLow);
DaysHigh=(TextView)findViewById(R.id.DaysHigh);
LastPrice=(TextView)findViewById(R.id.LastPrice);
Change=(TextView)findViewById(R.id.Change);
DailyPriceRange=(TextView)findViewById(R.id.DailyPriceRange);
setOnClickListener(enterbuttonlistener);
}
public OnClickListener enterbuttonlistener=new OnClickListener(){
公共void onClick(视图v){
如果(stocksymbol.getText().length()>0){
stocksymbolstring=stocksymbol.getText().toString();
stocksymbol.setText(“”;//清除编辑文本框
//强制关闭键盘
InputMethodManager imm=(InputMethodManager)getSystemService(
上下文。输入方法(服务);
imm.hideSoftInputFromWindow(stocksymbol.getWindowToken(),0);
}否则{
//创建警报对话框
AlertDialog.Builder=新建AlertDialog.Builder(MainActivity.this);
//设置警报标题
builder.setTitle(“无效库存符号”);
//为用户的积极反应设置值
//您还可以将侦听器设置为在按下时调用
builder.setPositiveButton(“确定”,null);
//信息
builder.setMessage(“缺少库存符号”);
//创建警报对话框并显示它
AlertDialog theAlertDialog=builder.create();
theAlertDialog.show();
}//结束其他
//创建YQL查询
最后一个字符串YQURL=yahooURLFirst+stocksymbolstring+yahooURLSecond;
新建MyAsyncTask().execute(yqlURL);
}//结束onClick视图v
};//结束按钮单击事件
私有类MyAsyncTask扩展了AsyncTask{
//字符串…arg0与字符串[]args相同
受保护的字符串doInBackground(字符串…args){
//新东西
试一试{
Log.d(“test”,“在XmlPullParser中”);
//建议使用XmlPullParser,因为
//与domapi相比,它速度更快,所需内存更少
//XmlPullParserFactory为您提供了
//创建解析XML文档的拉式解析器
XmlPullParserFactory工厂=XmlPullParserFactory.newInstance();
//解析器支持XML名称空间
factory.setNamespaceAw
int parserArrayIncrement = 0;
protected String doInBackground(
    int parserArrayIncrement = 0;