2014-04-01 4 views
2

필요한 모든 가져 오기가 있습니다. 누군가가 어쩌면 내 InputStream 읽을 수없는 이유에 대한 빛을 던질 수 있다면 크게 감사하겠습니다. 내 로그가 비동기 클래스에 문제를 반환하지만 이것이 입력 스트림이 주어진 URL로 읽히지 않는다고 생각된다. 미리 감사드립니다.Java에서 앱용 Wolfram Alpha API를 사용하려고하지만 Async 클래스에 문제가 있습니다.

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를 글로벌 varibale로 변경했습니다. 두 번 null로 설정했다. 그렇더라도 앱은 여전히 ​​비동기식으로 폭탄을 터뜨린다. 그것은 말한다 : "AsyncTask # 1에 치명적 예외" –

+0

감사합니다. Carl Anderson, 스택 오버플로를 처음 사용하는 것이고, 앞으로 그렇게 할 것입니다. –

답변

1

나는 문제는 당신이 좋은 연결을 얻지 못하고 있다는 것을 의심. 결과가 HTTP_OK하지 않은 경우 당신이 입력 스트림을 설정하는 코드의이 시점에서

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

하지만, 당신은 null를 반환 할거야, 당신은 OpenHttpConnection()을에도 제대로 그 가능성을 취급하지 않는 전화를 걸었던 wolframAnswer()도 아닙니다. 연결 설정 코드의 일부가 올바르게 연결되어 있지 않은 것 같습니다. 따라서 입력 스트림이 null이고 DocumentBuilder로 구문 분석하려고하면 충돌이 발생합니다.

+0

내가 옳다. 좋은 연결을 얻지 못했습니다. 그러나 이것은 OpenHttpConnection ("http://www.wolframalpha.com/v2/input="+ currencyVal + firstSelect + "-"secondSelect + "& appid = J6HA6V-YHRLHJ8A8Q") 섹션에서 파생됩니다. 코드의 일부. 이유 또는 다른 아무것도 OpenHttpConnection (String urlString) 전달되는 인수를 보내는 경우에도. –

+0

Logcat으로 로깅하는 방법을 알고 있습니까? http://developer.android.com/tools/debugging/debugging-log.html 잘못된 것의 맨 아래로 가려는 로깅 구문을 추가해야합니다. –

+0

당신은 정확합니다. 위의 답을 찾기 직전까지 그것을 격리했습니다. 응답 코드는 404이며, HTTP_OK 코드는 200이지만 404 오류가있는 것으로 추측됩니다. 404는 서버에서 필요한 응답을받지 못한다는 것을 의미합니다. 아마 URL에 오류가 있음을 의미 할 것입니다 ... –