我试图在Java中使用Wolfram Alpha API作为应用程序,但在异步类方面存在问题
我有所有必要的进口货。如果有人能解释一下为什么我的输入流没有被读取,我将不胜感激。我相信是这样的,因为我的日志返回了一个异步类的问题,但更进一步地说,输入流似乎没有被读取为给定的url(尽管我可能错了)。提前谢谢我试图在Java中使用Wolfram Alpha API作为应用程序,但在异步类方面存在问题,java,android,android-asynctask,http-get,wolframalpha,Java,Android,Android Asynctask,Http Get,Wolframalpha,我有所有必要的进口货。如果有人能解释一下为什么我的输入流没有被读取,我将不胜感激。我相信是这样的,因为我的日志返回了一个异步类的问题,但更进一步地说,输入流似乎没有被读取为给定的url(尽管我可能错了)。提前谢谢 public class MainActivity extends Activity { String[] currency; EditText amount1; TextView answer; Spinner spin1; Spinner spin2; private Inpu
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;
}
公共类MainActivity扩展活动{
字符串[]货币;
编辑文本数量1;
文本视图答案;
自旋器自旋1;
旋转器旋转2;
私有InputStream OpenHttpConnection(字符串urlString)引发IOException
{
InputStream in=null;
int响应=-1;
URL=新URL(URL字符串);
URLConnection conn=url.openConnection();
if(!(HttpURLConnection的连接实例))
抛出新IOException(“非HTTP连接”);
尝试
{
HttpURLConnection httpConn=(HttpURLConnection)conn;
httpConn.setAllowUserInteraction(假);
httpConn.setInstanceFollowRedirects(真);
httpConn.setRequestMethod(“GET”);
httpConn.connect();
response=httpConn.getResponseCode();
if(response==HttpURLConnection.HTTP\u OK)
{
in=httpConn.getInputStream();
}
}
捕获(例外情况除外)
{
Log.d(“Wolf Post”,例如getLocalizedMessage());
抛出新IOException(“连接错误”);
}
返回;
}
//方法发送信息并回调xml格式响应
私有字符串wolframAnswer(int currencyVal、字符串firstSelect、字符串secondSelect)
{
//变量是根据用户选择来分配的
int pos1=spin1.getSelectedItemPosition();
firstSelect=货币[pos1];
int pos2=spin2.getSelectedItemPosition();
secondSelect=货币[pos2];
amount1=(EditText)findViewById(R.id.editAmount1);
答案=(TextView)findViewById(R.id.txtResult);
InputStream in=null;
字符串strWolfReturn=“”;
尝试
{
in=OpenHttpConnection(“http://www.wolframalpha.com/v2/input=“+currencyVal+firstSelect+”-“+secondSelect+”&appid=J6HA6V-YHRLHJ8A8Q”);
单据单据=空;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
文档生成器数据库;
尝试
{
db=dbf.newDocumentBuilder();
doc=db.parse(in);
}
捕获(ParserConfiguration异常e)
{
e、 printStackTrace();
}
捕获(例外e)
{
e、 printStackTrace();
}
doc.getDocumentElement().normalize();
//检索wolfram假设
NodeList assumpElements=doc.getElementsByTagName(“假设”);
//通过假设来纠正错误
对于(int i=0;iif(response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
}