2014-04-01 63 views
2

我擁有所有必需的導入。如果有人可以拋出一些可能,爲什麼我的InputStream不被閱讀,將不勝感激。我相信這是因爲我的日誌返回一個問題與異步類,但進一步從它似乎是(我可能是錯誤的),輸入流不被讀爲給定的URL。提前致謝。我正在嘗試在Java中使用Wolfram Alpha API,但遇到異步類問題

public class MainActivity extends Activity { 

String[] currency; 
EditText amount1; 
TextView answer; 
Spinner spin1; 
Spinner spin2; 

private InputStream OpenHttpConnection(String urlString) throws IOException 
{ 
    InputStream in = null; 

    int response = -1; 

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection(); 

    if(!(conn instanceof HttpURLConnection)) 
     throw new IOException("Not an HTTP Connection"); 
    try 
    { 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 
     response = httpConn.getResponseCode(); 
     if(response == HttpURLConnection.HTTP_OK) 
     { 
      in = httpConn.getInputStream(); 
     } 

    } 
    catch(Exception ex) 
    { 
     Log.d("Wolf Post", ex.getLocalizedMessage()); 
     throw new IOException("Error Connecting"); 
    } 
    return in; 
} 

//method to send information and pull back xml format response 
private String wolframAnswer(int currencyVal, String firstSelect, String secondSelect) 
{ 
    //variables are assigned based of user select 
    int pos1 = spin1.getSelectedItemPosition(); 
    firstSelect = currency[pos1]; 

    int pos2 = spin2.getSelectedItemPosition(); 
    secondSelect = currency[pos2]; 

    amount1 = (EditText)findViewById(R.id.editAmount1); 
    answer = (TextView)findViewById(R.id.txtResult); 

    InputStream in = null; 

    String strWolfReturn = ""; 

    try 
    { 
     in = OpenHttpConnection("http://www.wolframalpha.com/v2/input="+currencyVal+firstSelect+"-"+secondSelect+"&appid=J6HA6V-YHRLHJ8A8Q"); 
     Document doc = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db; 

     try 
     { 
      db = dbf.newDocumentBuilder(); 
      doc = db.parse(in); 
     } 
     catch(ParserConfigurationException e) 
     { 
      e.printStackTrace(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 

     doc.getDocumentElement().normalize(); 

     //retrieve the wolfram assumptions 
     NodeList assumpElements = doc.getElementsByTagName("assumptions"); 

     //move through assumptions to correct one 
     for (int i = 0; i < assumpElements.getLength(); i++) 
     { 
      Node itemNode = assumpElements.item(i); 

      if(itemNode.getNodeType() == Node.ELEMENT_NODE) 
      { 
       //convert assumption to element 
       Element assumpElly = (Element) itemNode; 

       //get all the <query> elements under the <assumption> element 
       NodeList wolframReturnVal = (assumpElly).getElementsByTagName("query"); 

       strWolfReturn = ""; 

       //iterate through each <query> element 
       for(int j = 0; j < wolframReturnVal.getLength(); j++) 
       { 
        //convert query node into an element 
        Element wolframElementVal = (Element)wolframReturnVal.item(j); 

        //get all child nodes under query element 
        NodeList textNodes = ((Node)wolframElementVal).getChildNodes(); 

        strWolfReturn += ((Node)textNodes.item(0)).getNodeValue() + ". \n"; 
       } 
      } 

     } 



    } 
    catch(IOException io) 
    { 
     Log.d("Network activity", io.getLocalizedMessage()); 
    } 

    return strWolfReturn; 
} 
//using async class to run a task similtaneously with the app without crashing it 
private class AccessWebServiceTask extends AsyncTask<String, Void, String> 
{ 
    protected String doInBackground(String... urls) 
    { 
     return wolframAnswer(100, "ZAR", "DOL"); 
    } 
    protected void onPostExecute(String result) 
    { 
     Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show(); 
    } 
} 

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


    //spinner implementation from here down 
    currency = getResources().getStringArray(R.array.currencies); 

    spin1 = (Spinner)findViewById(R.id.spinCurr1); 
    spin2 = (Spinner)findViewById(R.id.spinCurr2); 

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, currency); 

    spin1.setAdapter(adapter); 
    spin2.setAdapter(adapter); 

    //using httpget to send request to server. 
    amount1 = (EditText)findViewById(R.id.editAmount1); 
    answer = (TextView)findViewById(R.id.txtResult); 

    Button convert = (Button)findViewById(R.id.btnConvert); 

    convert.setOnClickListener(new Button.OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      //apiSend(); 
      new AccessWebServiceTask().execute(); 
     } 

    }); 


} 

/*public void apiSend() 
{ 
    int pos1 = spin1.getSelectedItemPosition(); 
    String firstSelect = currency[pos1]; 

    int pos2 = spin2.getSelectedItemPosition(); 
    String secondSelect = currency[pos2]; 

    amount1 = (EditText)findViewById(R.id.editAmount1); 
    answer = (TextView)findViewById(R.id.txtResult); 

    Toast.makeText(getBaseContext(), "Converting...", Toast.LENGTH_LONG).show(); 

    try 
    { 
     //encoding of url data 
     String currencyVal = URLEncoder.encode(amount1.getText().toString(),"UTF-8"); 

     //object for sending request to server 
     HttpClient client = new DefaultHttpClient(); 

     String url = "http://www.wolframalpha.com/v2/input="+currencyVal+firstSelect+"-"+secondSelect+"&appid=J6HA6V-YHRLHJ8A8Q"; 

     try 
     { 

      String serverString = ""; 

      HttpGet getRequest = new HttpGet(url); 

      ResponseHandler<String> response = new BasicResponseHandler(); 

      serverString = client.execute(getRequest, response); 
      Toast.makeText(getBaseContext(), "work 1work 1work", Toast.LENGTH_SHORT).show(); 
      answer.setText(serverString); 
     } 
     catch(Exception ex) 
     { 
      answer.setText("Fail 1"); 
     } 
    } 
    catch(UnsupportedEncodingException ex) 
    { 
     answer.setText("Fail 2"); 
    } 

}*/ 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

+0

如果您只發布相關代碼部分,而不是整個文件,則您更有可能得到答覆。 –

+0

將InputStream更改爲全局變量。看到我將它設置爲空兩次。即使如此,該應用程序仍然在異步上爆炸。它說:「在AsyncTask#1上致命的例外」 –

+0

感謝Carl Anderson,這是我第一次使用堆棧溢出,將來會這樣做。 –

回答

1

我懷疑的問題是,你沒有得到一個很好的連接。

if(response == HttpURLConnection.HTTP_OK) 
{ 
    in = httpConn.getInputStream(); 
} 

在你設置的輸入流的代碼這一點,但如果結果不是HTTP_OK,你要回null,而你沒有正確處理這種可能性,無論是在OpenHttpConnection()也不在wolframAnswer()你稱之爲的地方。您的連接設置代碼似乎沒有正確連接,因此您的輸入流爲null,並且在嘗試使用DocumentBuilder解析它時崩潰。

+0

你是對的,我是沒有得到很好的連接,但是這源於in = OpenHttpConnection(「http://www.wolframalpha.com/v2/input=」+ currencyVal + firstSelect +「 - 」+ secondSelect +「&appid = J6HA6V-YHRLHJ8A8Q」); section的代碼。對於一些原因或其他什麼都沒有被傳遞給OpenHttpConnection(String urlString),即使我正在發送它的參數。 –

+0

你知道如何使用Logcat進行日誌記錄嗎? http://developer.android.com/tools/debugging/debugging-log.html 您應該添加一堆日誌記錄語句以試圖弄清楚發生了什麼問題。 –

+0

您先生,是正確的。我已經將它隔離到了上面的答案之前。響應代碼是404,我猜是404錯誤,而HTTP_OK代碼是200. 404意味着它沒有從服務器獲得必要的響應。這可能意味着網址中存在錯誤... –

相關問題