【发布时间】:2014-05-08 10:08:56
【问题描述】:
我需要用不同的 url 调用 asynctask。我有三个按钮,他们用不同的 url 向服务器发送 http 帖子,现在我可以用一个 url 调用 asynctask 但我如何用不同的 url 调用相同的函数。以下是我的 asynctask 类:
private class Downloadfiles extends AsyncTask<URL, Integer, JSONObject>{
@Override
protected void onPostExecute(JSONObject jo) {
try {
cards = jo.getInt("cards");
points = jo.getInt("points");
cash = jo.getInt("cash");
} catch (JSONException e1) {
e1.printStackTrace();
}
//cardsv.startAnimation(textio);
cardsv.setText(""+cards);
cashv.setText(""+cash);
Log.e("wintype", "msg" + wintype);
super.onPostExecute(jo);
}
@Override
protected JSONObject doInBackground(URL... params) {
Log.e("msg++--", "play game method called");
BufferedReader reader=null;
data_to_send = "userId=" + userId ;
try
{
Log.e("inside try block playgame", "get text" + data_to_send);
// Defined URL where to send data
URL url = new URL(playgame);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside playgame", "while loop");
}
play_response = sb.toString();
}
catch(Exception ex)
{
Log.e("MyTag ", "Failure to get json data in playgame--1--", ex);
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
Log.e("MyTag", "Failure to get json data in playgame--2--", ex);
}
}
Log.e("play response from the server in ", "play game" + play_response);
JSONObject jo = null;
try {
jo = new JSONObject(play_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jo;
}
}
我用我的一个按钮点击来调用它
Downloadfiles download = new Downloadfiles();
downloads.execute();
【问题讨论】:
-
downloads.execute(url1) 像这样你可以在执行中传递参数
-
我试过了,但是 URL url = new URL(playgame); URLConnection conn = url.openConnection();给我错误
-
这里的游戏是什么?你在哪里声明的??
-
@user3472186 在下面查看我的答案。
标签: java android android-asynctask